用树状数组求数组内的逆序对数

 1 #include<cstdio>
 2 #include<string.h>
 3 #include<iostream>
 4 #include<cstdlib>
 5 #include<algorithm>
 6 using namespace std;
 7 
 8 #define MAX_NUM 500010
 9 
10 struct node{
11     int value;
12     int id;
13 };
14 
15 int cmp(struct node a, struct node b)
16 {
17     return a.value < b.value;
18 }
19 
20 struct node values[MAX_NUM];
21 int hash[MAX_NUM];
22 long long tree_arr[MAX_NUM];
23 
24 int lowbit(int x)
25 {
26     return x&(-x);
27 }
28 
29 void update(int pos,int up)
30 {
31     while(pos<=up)
32     {
33         tree_arr[pos] +=1;
34         pos = pos + lowbit(pos);
35     }
36 }
37 
38 int get_sum(int pos)
39 {
40     long long ans = 0;
41     while(pos>0)
42     {
43         ans +=tree_arr[pos];
44         pos -= lowbit(pos);
45     }
46     return ans; 
47 }
48 
49 int main(void)
50 {
51     int N;
52     while(scanf("%d",&N) && N)
53     {
54         int i;
55         long long ans = 0;
56 
57         for(i = 0;i<N;i++)
58         {
59             scanf("%d",&values[i].value);
60             values[i].id = i+1;
61         }
62         sort(values,values+N,cmp);
63 
64         for(i = 1;i<=N;i++)
65         {
66             hash[values[i-1].id] = i;
67         }
68         memset(tree_arr,0,sizeof(tree_arr));
69         update(hash[1],N);
70         for(i = 2;i<=N;i++)
71         {
72             update(hash[i],N);
73             if(hash[i] == N)
74                 continue;
75             ans += get_sum(N)- get_sum(hash[i]);
76         }
77 
78         printf("%lld\n",ans);
79     }
80     return 0;
81 }
View Code

 

posted @ 2015-07-05 21:25  一麻袋码的玛侬  阅读(246)  评论(0编辑  收藏  举报