HDU 2689 sort it(树状数组 逆序数)

Problem Description
You want to processe a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. Then how many times it need.
For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.
 
Input
The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 1000); the next line contains a permutation of the n integers from 1 to n.
 
Output
For each case, output the minimum times need to sort it in ascending order on a single line.
 
Sample Input
3
1 2 3
4
4 3 2 1
 
Sample Output
0
6
 
为什么可以用逆序数呢,因为它要相邻两个交换,而逆序数,比如 4 3 2 1,比3大的1个,正好4,3交换,比2大的2个,4和3,2先和3换,再和4换。就算4和3先不进行交换,2与3交换,变成4 2 3 1,在3前面比3大的还是4,还是会通过2,4交换,然后再3,4交换,所以这题可以通过求逆序数解
AC代码:
 1 #include<cstdio>
 2 #include<cstring>
 3 const int N = 100000+5;
 4 int n;
 5 int c[N],a[N];
 6 
 7 int lowbit(int x) {
 8     return x&-x;
 9 }
10 
11 void add(int x, int a) {
12     while(x <= n) {
13         c[x] += a;
14         x += lowbit(x);
15     }
16 }
17 
18 int sum(int x) {
19     int ans = 0;
20     while(x) {
21         ans += c[x];
22         x -= lowbit(x);
23     }
24     return ans;
25 }
26 
27 int main(){
28     while(scanf("%d",&n)!=EOF) {
29         memset(c,0,sizeof(c));    
30         int ans=0;
31         for(int i = 1; i <= n; i++) {
32             scanf("%d",&a[i]);
33             add(a[i], 1);
34             ans += i-sum(a[i]);
35         }
36         printf("%d\n",ans);
37     }
38     return 0;
39 }

 

posted on 2019-01-21 21:07  甜甜圈不懂巧克力的苦  阅读(121)  评论(0编辑  收藏  举报

导航