只允许交换,比较相邻的元素, 求最少多少次交换可以使得序列有序
冒泡排序的次数——>数列中逆序对的个数减1——>最终为0 ——>答案为数列中逆序对的个数——> 归并排序求逆序对qwq
注意cnt开long long 不然会炸QAQ
板子!上!
1 #include<cstdio> 2 #include<cstring> 3 #include<iostream> 4 using namespace std; 5 const int sz = 500050; 6 int a[sz], b[sz], n; 7 long long cnt = 0; 8 void merge_sort(int l, int r) { 9 if(r-l > 0) {//这里一开始写成while了QAQ 死循环无输出orz 10 int mid = (l + r) >> 1; 11 int i = l, p = l, q = mid+1; 12 merge_sort(l, mid); 13 merge_sort(mid+1, r); 14 while(q<=r || p <= mid) { 15 if(q > r || ((p <= mid)&&(a[p] <= a[q]))) 16 b[i++] = a[p++]; 17 else b[i++] = a[q++], cnt = cnt + mid - p + 1; 18 } 19 for(int i = l; i <= r; i++) 20 a[i] = b[i]; 21 } 22 } 23 int main() { 24 while(1) { 25 scanf("%d", &n); 26 if(n==0) break; 27 memset(a, 0, sizeof(a)); 28 memset(b, 0, sizeof(b)); 29 for(int i = 1; i <= n; i++) 30 scanf("%d", &a[i]); 31 cnt = 0; 32 merge_sort(1, n); 33 printf("%lld ", cnt); 34 } 35 36 }