InversionTime
limit:2000/1000 MS (java/others) Memory limit:131072/131072 K (java/others)
Total submission (s): 3171 Accepted Submission (s): 1154
Problem Descriptionbobo has a sequence a1,a2,...,. He is allowed to swap
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
The main idea: to give a series of numbers, in order to make the most of the K-number of adjacent numbers after the exchange, how many reverse number pairs;
Problem-solving idea: To find out the inverse number of the original sequence in the order of CNT, then Max (cnt-k, 0), which is the answer;
#include "iostream" #include "Cstdio" #include "CString" using namespace Std;int a[100005];int b[100005];//Auxiliary array Long Long Cnt;void Merge (int a[],int p,int q,int r, int b[]) {int s = p, t = q + 1, k = P;while (s <= q && t <= r) {if (a [s] <= a[t]) {b[k + +] = A[s + +];} Else{b[k + +] = a[t ++];cnt + = (q-s + 1);//In the original sequence A[S...Q] > a[t], there is an inverse number pair (q-s+1)}}if (s = = q + 1) for (; t <= r;t + +) B[k + +] = a[t];elsefor (; s <= q;s + +) B[k + +] = a[s];for (int i = P;i < K;i + +) a[i] = B[i];} void Bottomupsort (int a[],int first,int last,int b[]) {if (first < last) {int mid = (first + last)/2; Bottomupsort (A, first, Mid, b); Bottomupsort (A, mid + 1, last, b); Merge (A, first, mid, last, b);}} int main () {int n, k;while (scanf ("%d%d", &n,&k)! = EOF) {cnt = 0;for (int i = 1;i <= n;i + +) scanf ("%d", &a[i]); B Ottomupsort (a,1,n, b); cnt = (cnt-k) > 0? (cnt-k): 0;//for (int i = 1;i <= n;i + +) printf ("%d", A[i]);p rintf ("\ n");p rintf ("%i64d\n", CNT);} return 0;}
Inversion (hdu_4911) Merge sort + reverse order number pair