标签:
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 44671 | Accepted: 16240 |
Description
Input
Output
Sample Input
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0
----------------------------------------------------------------------------------------------------------------
题目是求逆序对,可以通过快排或者归并算法得出逆序数然后输出。
------------------------------------------------------
#include <stdio.h> #include <stdlib.h> __int64 sum = 0; void mergeSort(int arr[], int first, int last, int temp[]) { if (first < last) { int mid = (first + last) / 2; mergeSort(arr, first, mid, temp); mergeSort(arr, mid + 1, last, temp); mergeArray(arr, first, mid, last, temp); } } void mergeArray(int arr[], int first, int mid, int last, int temp[]) { int i = first, j = mid + 1; int m = mid, n = last; int k = 0; while (i <= m && j <= n) { if (arr[i] < arr[j]) { temp[k++] = arr[i++]; } else { temp[k++] = arr[j++]; sum += m - i + 1; } } while (i <= m) { temp[k++] = arr[i++]; } while (j <= n) { temp[k++] = arr[j++]; } for (i = 0; i < k; i++) { arr[first + i] = temp[i]; } } void MergeSort(int arr[], int n) { int *p = (int *)malloc(500000); if (p) { mergeSort(arr, 0, n - 1, p); //free(p); } } int main() { int head; int a[500000]; //freopen("D:\\test.txt", "r", stdin); while(1) { scanf("%d", &head); if (head == 0) break; int i; for (i = 0; i < head; i++) { scanf("%d", &a[i]); } sum = 0; MergeSort(a, head); printf("%I64d\n", sum); } return 0; }
标签:
原文地址:http://www.cnblogs.com/codingpenguin/p/4286585.html