NYOJ 322 Sort (归并排序求逆序数) (树状数组求逆序数)

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=322

如果按冒泡排序这些O(n^2)肯定会超时,所以需要找一种更快的方法 --------归并排序。

归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为2-路归并。这题还可以用树状数组来做

 1  法一:用归并排序做
 2 #include<stdio.h>
 3 int a[1000001],b[1000001]; /*合并排序结果先保存到b中*/
 4 int merge(int a[],int low,int mid,int high)
 5 {
 6     int i=low,j=mid+1,k=low;
 7     int count=0;/*计数器*/ 
 8     while((i<=mid)&&(j<=high))/*部分合并*/
 9     {
10         if(a[i]<=a[j])
11         {
12             b[k++]=a[i++];
13         }
14         else
15         {
16             b[k++]=a[j++];
17             count+=(mid-i+1);
18         }
19     }
20     while(i<=mid)/*转储剩余部分*/
21     {
22         b[k++]=a[i++];
23     }
24     while(j<=high)
25     {
26         b[k++]=a[j++];
27         
28     }
29     for(i=low;i<=high;++i)/*把b中的值复制给a*/
30     {
31         a[i]=b[i];
32     }
33     return count;
34 }
35 int sort(int a[],int low,int high)
36 {
37     int x,y,z;
38     int mid=(high+low)/2;
39     int i=low,j=mid+1;
40     if(low>=high)
41     {
42         return 0;
43     }
44     x=sort(a,low,mid);
45     y=sort(a,mid+1,high);
46     z=merge(a,low,mid,high);
47     return (x+y+z);
48 }
49 int main()
50 {
51     int ncases,n,i;
52     scanf("%d",&ncases);
53     while(ncases--)
54     {
55         scanf("%d",&n);
56         for(i=0;i<=n-1;i++)
57         {
58             scanf("%d",&a[i]);
59         }
60         printf("%d\n",sort(a,0,n-1));
61     }
62     return 0;
63 }                        

 法二:用树状数组

 不知道什么是树状数组的  就先看看树状数组吧。。链接:http://dongxicheng.org/structure/binary_indexed_tree/

 3 #include<stdio.h>
 4 #include<string.h>
 5 int num[1004],n;
 6 int lowbit(int x)
 7 {
 8     return x&(-x);
 9 }
10 void add(int x)
11 //更新含有x的数组个数
12 {
13     while(x<=n)
14     {
15         num[x]++;
16         x+=lowbit(x);
17     }
18 }
19 int sum(int x)
20 //向下统计小于x的个数
21 {
22     int total=0;
23     while(x>0)
24     {
25         total+=num[x];
26         x-=lowbit(x);
27     }
28     return total;
29 }
30 int main()
31 {
32     int x,cases;
33     scanf("%d",&cases);
34     while(cases--)
35     {
36         scanf( "%d",&n);
37         memset( num,0,sizeof( num ));
38         int ss = 0;
39         for( int i = 0; i < n; ++i )
40         {
41             scanf( "%d",&x);
42             add(x);
43             ss += (i-sum( x - 1 ));
44         }
45         printf( "%d\n",ss );
46     }
47     return 0;
48 }
49         

 

 

posted on 2012-08-10 16:31  mycapple  阅读(286)  评论(0编辑  收藏  举报

导航