Topic Connection: http://acm.hdu.edu.cn/showproblem.php?pid=1394
Segment Tree function: Update: Single point of increase or decrease query: interval sum
Analysis: If the arrangement is 0 to n-1, then if the first number is put to the last, for this series, the reverse number is reduced a[i], and increase n-1-a[i], so each change to res+=n-a[i]-1-a[i].
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#defineLL Long Long#defineMAXN 5555#defineLson l,m,rt<<1#defineRson m+1,r,rt<<1|1using namespacestd;intsum[maxn<<2];intA[MAXN];voidPushup (intRT) {Sum[rt]=sum[rt<<1]+sum[rt<<1|1];}voidBuildintLintRintRT) {Sum[rt]=0; if(l==R)return; intM= (r+l) >>1; Build (Lson); Build (Rson);}voidUpdateintPosintLintRintRT) { if(r==l) {Sum[rt]++; return; } intM= (r+l) >>1; if(pos<=m) update (Pos,lson); ElseUpdate (Pos,rson); Pushup (RT);}intQuery (intLintRintLintRintRT) { if(l<=l&&r<=R) {returnSum[rt]; } intM= (r+l) >>1; intres=0; if(l<=m) res+=Query (L,r,lson); if(M<r) res+=Query (L,r,rson); returnRes;}intMain () {intN; while(SCANF ("%d", &n) >0) {Build (0, N-1,1); intsum=0; for(intI=0; i<n;i++) {scanf ("%d",&A[i]); Sum+=query (a[i],n-1,0, N-1,1); Update (A[i],0, N-1,1); } intans=sum; for(intI=0; i<n;i++) {sum+=n-a[i]-a[i]-1; Ans=min (ans,sum); } printf ("%d\n", ans); } return 0;}
View Code
The tree-like array is easier to find in reverse order ...
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#defineLL Long Long#defineMAXN 5555#defineLson l,m,rt<<1#defineRson m+1,r,rt<<1|1using namespacestd;intA[MAXN],C[MAXN];intN;intLowbit (intx) { returnx& (-x);}intSuminti) { intres=0; while(i) {res+=C[i]; I-=lowbit (i); } returnRes;}voidUpdateintIintx) { while(i<=N) {C[i]+=x; I+=lowbit (i); }}intMain () { while(SCANF ("%d", &n) >0) { intres=0; Memset (c,0,sizeof(c)); for(intI=1; i<=n;i++) {scanf ("%d",&A[i]); A[i]++; Res+=i-1-sum (A[i]);//1~a[i] The number of occurrences of the interval, the total (i-1)-sum (A[i]) can beUpdate (A[i],1);//single-point update } intans=Res; for(intI=1; i<=n;i++) {res+=n-a[i]-(a[i]-1); Ans=min (ans,res); } printf ("%d\n", ans); }}
View Code
hdu1394 (segment tree for reverse order)