您的位置:首页 > 其它

【归并排序求逆序对个数】【树状数组求逆序对个数】

2017-09-03 16:48 399 查看
【AC】

1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #include<string>
5 #include<cmath>
6 #include<algorithm>
7 using namespace std;
8 typedef long long ll;
9 const int maxn=5e5+2;
10
11 int n;
12 ll ans;
13 struct node
14 {
15     int x;
16     int pos;
17 }a[maxn];
18 int tree[maxn];
19 int r[maxn];
20 bool cmp(node nd1,node nd2)
21 {
22     return nd1.x<nd2.x;
23 }
24 int lowbit(int x)
25 {
26     return x&-x;
27 }
28 void add(int k,int x)
29 {
30     while(k<=n)
31     {
32         tree[k]+=x;
33         k+=lowbit(k);
34     }
35 }
36 ll query(int k)
37 {
38     ll ans=0;
39     while(k)
40     {
41         ans+=tree[k];
42         k-=lowbit(k);
43     }
44     return ans;
45 }
46 int main()
47 {
48     while(scanf("%d",&n)&&n)
49     {
50         for(int i=1;i<=n;i++)
51         {
52             scanf("%d",&a[i].x);
53             a[i].pos=i;
54         }
55         sort(a+1,a+n+1,cmp);
56         for(int i=1;i<=n;i++)
57         {
58             r[a[i].pos]=i;
59         }
60         memset(tree,0,sizeof(tree));
61         ans=0;
62         for(int i=1;i<=n;i++)
63         {
64             add(r[i],1);
65             ans+=i-query(r[i]);
66         }
67         cout<<ans<<endl;
68     }
69     return 0;
70 }


树状数组求逆序对个数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐