Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=1394
Test instructions: give you a 0-n-1 arrangement, for this arrangement you can put the first element to the last, and ask the number of reverse pairs you might get
The number of reverse pairs of the original sequence is calculated, then the first element is n-1 to the last operation, and the number of reverse pairs of the new sequence can be obtained with O (1) complexity after each operation.
The key point of this problem is to find out the number of reverse pairs in the original sequence, you can use tree array, segment tree, merge and other methods.
Here is the solution to the tree array
#include <iostream>#include<cstdio>#include<algorithm>#defineMAXN 5010using namespacestd;intC[MAXN], ARR[MAXN], N;intLowbit (intx);voidAddintXintu);intSumintx);intMainvoid){ while(SCANF ("%d", &n)! =EOF) { intAns =0; Memset (c,0,sizeof(c)); for(inti =0; I < n; ++i) {scanf ("%d", arr +i); Arr[i]+=1; Ans+ = i-sum (arr[i]); Add (Arr[i],1); } intPre =ans, tmp; for(inti =0; I < n-1; ++i) {tmp= Pre-(Arr[i]-1) + (N-Arr[i]); Ans=min (ans, tmp); Pre=tmp; } printf ("%d\n", ans); } return 0;}intLowbit (intx) { returnx& (-x);}intSumintx) { intresult =0; while(X >0) {result+=C[x]; X-=lowbit (x); } returnresult;}voidAddintXintu) { while(x <=N) {c[x]+=u; X+=lowbit (x); }}
HDU 1394 Minimum Inversion number (tree-like array)