Question link: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 4911
Inversion
Time Limit: 2000/1000 MS (Java/others) memory limit: 131072/131072 K (Java/Others)
Total submission (s): 528 accepted submission (s): 228
Problem descriptionbobo has a sequence A1, A2 ,..., An. He is allowed to swap two
AdjacentNumbers for no more than K times.
Find the minimum number of inversions after his swaps.
Note: The number of inversions is the number of pair (I, j) where 1 ≤ I <j ≤ n and AI> AJ. inputthe input consists of several tests. For each tests:
The first line contains 2 integers n, k (1 ≤ n ≤ 105,0 ≤ k ≤ 109). The second line contains N integers A1, A2 ,..., An (0 ≤ AI ≤ 109). outputfor each tests:
A single integer denotes the minimum number of inversions. sample input
3 12 2 13 02 2 1
Sample output
12
Authorxiaoxu Guo (ftiasch) source2014 multi-university training contest 5
Solution: calculate the number of reverse orders of the given sequence, and then subtract K. If it is less than zero, it will go to zero!
The Code is as follows: (Merge Sorting)
# Include <stdio. h> int is1 [112345], is2 [112345]; // is1 is the original array, is2 is the temporary array, and N is the personal defined length _ int64 merge (INT low, int mid, int high) {int I = low, j = Mid + 1, K = low ;__ int64 COUNT = 0; while (I <= Mid & J <= high) if (is1 [I] <= is1 [J]) // This is the key to stable sorting, cannot be less than is2 [k ++] = is1 [I ++]; else {is2 [k ++] = is1 [J ++]; count + = J-K; // record the advance distance whenever the array element in the back segment advances} while (I <= mid) is2 [k ++] = is1 [I ++]; while (j <= high) is2 [k ++] = is1 [J ++]; for (I = low; I <= high; I ++) // write back the original array is1 [I] = is2 [I]; retur N count ;:__ int64 mergesort (int A, int B) // subscript. For example, if the array Int Is [5], the call to all sorts is mergesort) {if (a <B) {int mid = (a + B)/2 ;__ int64 COUNT = 0; count + = mergesort (A, mid ); count + = mergesort (Mid + 1, B); count + = Merge (A, mid, B); Return count ;}return 0 ;}int main () {int N, X ;__ int64 K ;__ int64 sum; while (scanf ("% d % i64d", & N, & K )! = EOF) {for (INT I = 0; I <n; I ++) {scanf ("% d", & X); is1 [I] = x ;} __int64 ans = mergesort (0, n-1); sum = 0; printf ("% i64d \ n", ANS-k> 0? Ans-K: 0);} return 0 ;}