- 题目大意
给出长度为n的序列,每次只能交换相邻的两个元素,问至少要交换几次才使得该序列为递增序列。
- 解题思路
利用归并排序来求逆序数(特别注意数组的大小,太大的话再开个数组分开装)。
- 代码
#include<iostream> #include<cstring> using namespace std; const long long MAX = 500001; long long num[MAX]; long long num1[MAX]; long long sum; void find(int l, int r) { if (l + 1 < r) { int m = l + (r - l) / 2; int p = l, q = m, i = l; find(l, m); find(q, r); while (p < m || q < r) { if (q >= r || (p < m&&num[p] <= num[q])) num1[i++] = num[p++]; else { num1[i++] = num[q++]; sum += m - p; } } for (int i =l; i < r; i++) num[i] = num1[i]; } } int main() { int m; while (cin >> m) { if (m == 0) break; sum = 0; memset(num, 0, sizeof(num)); memset(num1, 0, sizeof(num1)); for (int j = 0; j <m; j++) cin >> num[j]; find(0, m); cout << sum << endl; } return 0; }