归并排序模板

逆序对永远只会树状数组写法OrzOrzOrz……

 

 1 #include <stdio.h>
 2 
 3 const int _N = 12000;
 4 
 5 int A[_N], B[_N], cnt;
 6 
 7 void Merge(int l, int r)
 8 {
 9     int i, j, k, mid;
10     mid = l+r >> 1;
11     i = k = l, j = mid+1;
12     while (i <= mid && j <= r)
13         if (A[i] <= A[j]) B[k++] = A[i++];
14         else B[k++] = A[j++], cnt += mid-i+1;
15     while (i <= mid) B[k++] = A[i++];
16     while (j <= r) B[k++] = A[j++];
17     for (i = l; i <= r; ++i) A[i] = B[i];
18     return;
19 }
20 
21 void MergeSort(int l, int r)
22 {
23     if (l >= r) return;
24     int mid = l+r >> 1;
25     MergeSort(l, mid), MergeSort(mid+1, r);
26     Merge(l, r);
27     return;
28 }
29 
30 int main()
31 {
32     int i, N;
33     scanf("%d", &N);
34     for (i = 1; i <= N; ++i) scanf("%d", &A[i]);
35     MergeSort(1, N);
36     for (i = 1; i <= N; ++i) printf("%d ", A[i]);
37     printf("\nNiXuDuiShu: %d\n", cnt);
38     return 0;
39 }

 

posted @ 2018-07-11 15:20  derchg  阅读(279)  评论(0编辑  收藏  举报