PKU 2299

Ultra-QuickSort

题型:求逆序数

解法一:正统做法,归并排序,375MS。

  
    
1 #include " stdio.h "
2   #define N 500000
3 int num[N], temp[N];
4 __int64 sum;
5
6 void Merge( int * a, int start, int mid, int end)
7 {
8 int i = start, j = mid + 1 , k = 0 ;
9 while (i <= mid && j <= end) {
10 if (a[i] <= a[j])
11 temp[k ++ ] = a[i ++ ];
12 else {
13 temp[k ++ ] = a[j ++ ];
14 sum += mid-i+1 ; //出现逆序时,交换的次数
15 }
16 }
17 while (i <= mid)
18 temp[k ++ ] = a[i ++ ];
19 while (j <= end)
20 temp[k ++ ] = a[j ++ ];
21 for (i = 0 ; i < k; i ++ )
22 a[start + i] = temp[i];
23 }
24
25 void MergeSort( int * a, int start, int end)
26 {
27 int mid;
28 mid = (end + start) >> 1 ;
29 if (start < end) {
30 MergeSort(a, start, mid);
31 MergeSort(a, mid + 1 , end);
32 Merge(a, start, mid, end);
33 }
34 }
35
36 int main()
37 {
38 int n, i;
39 while (scanf( " %d " , & n), n) {
40 for (i = 0 ; i < n; i ++ )
41 scanf( " %d " , & num[i]);
42 sum = 0 ;
43 MergeSort(num, 0 , n - 1 );
44 printf( " %I64d\n " , sum);
45 }
46 return 0 ;
47 }
48

解法二:树状数组,需要先离散化,因为用到qsort(),比归并排序稍慢,516MS。

  
    
1 #include < stdio.h >
2 #include < stdlib.h >
3 #include < string .h >
4 #define NL 500000
5 #define LL long long
6
7 struct A {
8 int a, id;
9 }q[NL];
10 int f[NL], p[NL]; //f数组的意义:数字p[i]后边比其小的数的个数。
11 int n;
12
13 int cmp( const void * a, const void * b)
14 {
15 return (( struct A * )a) -> a - (( struct A * )b) -> a;
16 }
17
18 int sum( int idx)
19 {
20 int cnt = 0 ;
21 while (idx > 0 ) {
22 cnt += f[idx];
23 idx -= idx & ( - idx);
24 }
25 return cnt;
26 }
27
28 void update( int idx, int c)
29 {
30 while (idx <= n) {
31 f[idx] += c;
32 idx += idx & ( - idx);
33 }
34 }
35
36 int main()
37 {
38 int i;
39 LL cnt;
40 while (scanf( " %d " , & n) != EOF) {
41 if ( ! n) break ;
42 for (i = 1 ; i <= n; i ++ ) {
43 scanf( " %d " , & q[i].a);
44 q[i].id = i;
45 }
46 qsort(q + 1 , n, sizeof (q[ 0 ]), cmp);
47 for (i = 1 ; i <= n; i ++ ) {
48 p[q[i].id] = i;
49 f[i] = 0 ;
50 }
51 cnt = 0 ;
52 for (i = n; i > 0 ; i -- ) {
53 cnt += sum(p[i] - 1 );
54 update(p[i], 1 );
55 }
56 printf( " %lld\n " , cnt);
57 }
58 return 0 ;
59
60 }
61

 

你可能感兴趣的:(pku)