1010. Lehmer Code (35)

来源:互联网 发布:stata 面板数据 编辑:程序博客网 时间:2024/06/01 09:38

According to Wikipedia: "In mathematics and in particular in combinatorics, theLehmer code is a particular way to encode each possible permutation of a sequence ofn numbers." To be more specific, for a given permutation of items {A1, A2, ..., An}, Lehmer code is a sequence of numbers {L1, L2, ..., Ln} such that Li is the total number of items from Ai to An which are less than Ai. For example, given {24, 35, 12, 1, 56, 23}, the second Lehmer code L2 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 (<= 105). 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:
624 35 12 1 56 23
Sample Output:
3 3 1 0 1 0

求数组中每个数之后比它大的数的个数,简单粗暴的方法当然是不能通过的。这里学到了一种新的方法,用树状数组解决求逆序数的问题。树状数组在求一段区域的和方面比较有用,在这里通过计算每个数前面比它小的数的个数来求得答案,参考树状数组求逆序数。先对数组进行排序求得各个数的排名,然后依次插入到树状数组中,就能求得比当前点小的点有多少个已经插入到相应位置,然后用这个数排名减去当前比该数小的点数就能得到还有多少个比它小的数在后面,也就是我们要求的。


代码:

#include <iostream>#include <cstring>#include <vector>#include <cstdlib>#include <algorithm>using namespace std;#define N 100005int cnt[N];struct num{int val;int pos;};bool cmp(const num& x,const num& y){return x.val<y.val;}int lowbit(int n){return n&(-n);}int sum(int n){int ret=0;while(n>0){ret+=cnt[n];n-=lowbit(n);}return ret;}void getcnt(int k,int n){while(k<=n){cnt[k]++;k+=lowbit(k);}}int main(){    int n;    cin>>n;    memset(cnt,0,sizeof(cnt));    vector<num>vec(n+1);    for(int i=1;i<=n;i++)    {    cin>>vec[i].val;    vec[i].pos=i;    }    sort(vec.begin()+1,vec.end(),cmp);    vector<int>res(n);    vector<int>rank(n+1);    for(int i=1;i<=n;i++)    {    rank[vec[i].pos]=i;    }    for(int i=1;i<=n;i++)    {    getcnt(rank[i],n);    res[i-1]=rank[i]-sum(rank[i]);    }    cout<<res[0];    for(int i=1;i<n;i++)    {    cout<<" "<<res[i];    }    cout<<endl;    return 0;}


0 0
原创粉丝点击