1010. Lehmer Code (35)

本文介绍了一种利用树状数组计算排列中每个元素之后比其大的元素数量的方法,即Lehmer码的计算过程。通过示例输入输出展示了如何通过排序和树状数组更新来快速获取Lehmer码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 {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:
6
24 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 100005
int 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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值