1010 Lehmer Code (35 分)(C++)

欢迎访问我的PAT顶级题解目录

According to Wikipedia: "In mathematics and in particular in combinatorics, the Lehmer code is a particular way to encode each possible permutation of a sequence of n numbers." To be more specific, for a given permutation of items {A​1​​, A​2​​, ⋯, A​n​​}, Lehmer code is a sequence of numbers {L​1​​, L​2​​, ⋯, L​n​​} such that L​i​​ is the total number of items from A​i​​ to A​n​​ which are less than A​i​​. For example, given { 24, 35, 12, 1, 56, 23 }, the second Lehmer code L​2​​ is 3 since from 35 to 23 there are three items, { 12, 1, 23 }, less than the second item, 35.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10​5​​). Then N distinct numbers are given in the next line.

Output Specification:

For each test case, output in a line the corresponding Lehmer code. The numbers must be separated by exactly one space, and there must be no extra space at the beginning or the end of the line.

Sample Input:

6
24 35 12 1 56 23

Sample Output:

3 3 1 0 1 0

题目大意:给出一个序列,对该序列中的每一个数,计算它的右边比他小的数字的个数。

解题思路:本题是1009的改编,我们可以使用树状数组和平衡二叉树

树状数组

与1009不同的是,我们需要先对序列进行处理,以24 35 12 1 56 23为例,改写成3,4,1,0,5,2,即他们的大小序号,可以利用map会根据value进行排序的特性达到改写的目的。

在维护树状数组的时候可以从右往左进行update。

#include <bits/stdc++.h>
#define lowbit(i) ((i) & (-i))
using namespace std;
const int maxn = 100005;
int c[maxn];
void update(int x, int val){
	for(int i = x; i < maxn; i += lowbit(i))
		c[i] += val;
}
int getSum(int x){
	int ans = 0;
	for(int i = x; i >= 1; i -= lowbit(i))
		ans += c[i];
	return ans;
}
int main(){
	int n, temp, cnt = 0;
	scanf("%d", &n);
	vector<int> a(n);
	map<int, int> m;
	for(int i = 0; i < n; ++ i){
		scanf("%d", &temp);
		m[temp] = i;
	}
	for(auto it = m.begin(); it != m.end(); ++ it)
		a[(*it).second] = ++cnt;
	for(int i = n-1; i >= 0; -- i){
		update(a[i], 1);
		a[i] = getSum(a[i]-1); 
	}
	printf("%d", a[0]);
	for(int i = 1; i < n; ++ i)
		printf(" %d", a[i]);
}

平衡二叉树

用平衡二叉树不需要改写序列,更简单

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
int main(){
	tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> tr;
	int n;
	scanf("%d", &n);
	vector<int> a(n);
	for(int i = 0; i < n; ++ i)
		scanf("%d", &a[i]);
	for(int i = n-1; i >= 0; -- i){
		tr.insert(a[i]);
		a[i] = tr.order_of_key(a[i]);
	}
	printf("%d", a[0]);
	for(int i = 1; i < n; ++ i)
		printf(" %d", a[i]);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章