ZOJ 2386 今天最后一道题了,晚上要比赛,用了某大神的模板。加了个计数

View Code
 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #include<string.h>
 4 #define N 500000
 5 
 6 int a[N],b[N];
 7 long long count;
 8 void mergearray(int a[], int first, int mid, int last, int temp[])  
 9 {  
10     int i = first, j = mid + 1;  
11     int m = mid,   n = last;  
12     int k = 0;  
13       
14     while (i <= m && j <= n)  
15     {  
16         if (a[i] < a[j])  
17             temp[k++] = a[i++];  
18         else
19         {  
20             temp[k++] = a[j++];  
21            count += (m-i+1);//记录交换的次数
22          }   
23     }  
24       
25     while (i <= m)  
26         temp[k++] = a[i++];       
27     while (j <= n)  
28         temp[k++] = a[j++];        
29     for (i = 0; i < k; i++)  
30         a[first + i] = temp[i];  
31 }  
32 
33 void mergesort(int a[], int first, int last, int temp[])  
34 {  
35     if (first < last)  
36     {  
37         int mid = (first + last) / 2;  
38         mergesort(a, first, mid, temp);      
39         mergesort(a, mid + 1, last, temp);
40         mergearray(a, first, mid, last, temp); 
41     }  
42 }  
43   
44 int main()
45 {
46     int i,j,ncases,temp;
47     
48     while(scanf("%d",&ncases) && ncases)
49     {
50        for(i=0; i<ncases; i++)
51          scanf("%d",&a[i]);
52         count = 0;
53        mergesort(a,0,ncases-1,b);       
54         printf("%lld\n",count);
55     } 
56     return 0;
57 }
58      

 

posted @ 2012-08-04 17:18  zhongya  阅读(115)  评论(0编辑  收藏  举报