Time Limit: 3000MS |
|
Memory Limit: 65536KB |
|
64bit IO Format: %i64d &%i64u |
Description
You have a sequence\{a_1,a_2,..., a_n\} and you can delete a contiguous subsequence of length m. The minimum number of inversions after the deletion.
Input
There is multiple test cases. The first line of input contains an integerT, indicating the number of test cases. For each test case:
The first line contains integersN, m (1 \le n \le 10^5, 1 \le m < n) -the length of the seuqence. The second line contains n integersa_1,a_2,..., a_n (1 \le a_i \le N).
The sum of N in the test cases would not exceed 2 \times 10^6.
Output
For each test case, output the minimum number of inversions.
Sample Input
23 11 2 34 24 1 3 2
Sample Output
01
Source
Bestcoder Round #58 (Div.2)
Slide interval scan. Use a tree-like array to maintain the number of reverse pairs (the number of array storage n has occurred, by calculating the array prefix and the reverse order, the idea and the earlier written POJ2182 Lost cows similar)
Maintain the number of L ([i]) tree arrays that represent the number of I left than A[i], and the R ([i]) tree array represents the number of small numbers of I right than a[i]. The window slides from left to right, constantly updating L and R, calculating answers and updating
1 /*by Silvern*/2#include <iostream>3#include <algorithm>4#include <cstring>5#include <cstdio>6#include <cmath>7 using namespacestd;8 Const intmxn=110000;9 intn,m;Ten structtree{ One intA[MXN]; AInline Lowbit (intx) {returnx&-x;} - voidInit () {memset (A,0,sizeofa);} - voidAddintXintnum) { the while(x<=N) { -a[x]+=num; -x+=lowbit (x); - } + return; - } + intSumintx) { A intres=0; at while(x) { -res+=A[x]; -x-=lowbit (x); - } - returnRes; - } in }; - intA[MXN]; to tree Le,ri; + intMain () { - intT; thescanf"%d",&T); * while(t--){ $scanf"%d%d",&n,&m);Panax Notoginseng inti,j; - for(i=1; i<=n;i++){ thescanf"%d",&a[i]); + } A le.init (); the ri.init (); + Long Longans; - Long Longtmp=0; $ //logarithm of the original reverse order (not counted in the left-most sliding window) $ for(i=n;i>m;i--){ -Ri.add (A[i],1); -Tmp+=ri.sum (a[i]-1); the } -ans=tmp;Wuyi //Finish the for(i=1; i<=n-m;i++){ -Ri.add (a[i+m],-1);//The window is sliding and the rightmost number of the window is deleted . WuTmp=tmp+ri.sum (a[i]-1)-ri.sum (a[i+m]-1); -Tmp=tmp+le.sum (n+1-(a[i]+1))-le.sum (n+1-(a[i+m]+1)); AboutLe.add (n+1-a[i],1); $ans=min (ans,tmp); - } -printf"%lld\n", ans); - } A return 0; +}
HDU 5497 Inversion