题目描述
猫猫TOM和小老鼠JERRY最近又较量上了,但是毕竟都是成年人,他们已经不喜欢再玩那种你追我赶的游戏,现在他们喜欢玩统计。最近,TOM老猫查阅到一个人类称之为“逆序对”的东西,这东西是这样定义的:对于给定的一段正整数序列,逆序对就是序列中ai>aj且i<j的有序对。知道这概念后,他们就比赛谁先算出给定的一段正整数序列中逆序对的数目。
输入输出格式
输入格式:
第一行,一个数n,表示序列中有n个数。
第二行n个数,表示给定的序列。
输出格式:
给定序列中逆序对的数目。
输入输出样例
说明
对于50%的数据,n≤2500
对于100%的数据,n≤40000。
解析:
-
用一个结构体储存所输入数的编号(id)、和自身的值(val)
-
因为要用sort排序,所以要重载小于号,我们修改为从大往小排
之所以这样操作,自然是有目的的:
1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|
5 | 4 | 2 | 6 | 3 | 1 |
按从大到小以id号插入:
1 | 2 | 3 | 4 | 5 | 6 | ans |
---|---|---|---|---|---|---|
1 | ans=0 | |||||
1 | 1 | ans=0 | ||||
1 | 1 | 1 | ans=ans+1==1 | |||
1 | 1 | 1 | 1 | ans=ans+3==4 | ||
1 | 1 | 1 | 1 | 1 | ans=ans+2==6 | |
1 | 1 | 1 | 1 | 1 | 1 | ans=ans+5==11 |
口诀:找往前找,存往后存
代码如下:
#include<stdio.h> #include<algorithm> using namespace std; int n,ans,y[400001]; struct num{ int id,val; }poi[400001]; bool cmp(num a,num b){ return a.val>b.val; } int lowbit(int x){ return x&-x; } int Sol(int x){ int tot=0; while(x){ tot+=y[x]; x-=lowbit(x); } return tot; } void add(int x){ while(x<=n){ y[x]++; x+=lowbit(x); } } int main() { scanf("%d",&n); for(int i=1;i<=n;++i){ scanf("%d",&poi[i].val); poi[i].id=i; } sort(poi+1,poi+1+n,cmp); for(int i=1;i<=n;++i){ ans+=Sol(poi[i].id); add(poi[i].id); } printf("%d",ans); return 0; }