[USACO10NOV]奶牛的图片Cow Photographs 树状数组 递推
Code:
#include<cstdio> #include<algorithm> #include<string> #include<cstring> using namespace std; const int maxn=1000000+4; int n,C[maxn]; struct Data_Structure{ int lowbit(int t){ return t&(-t); } void add(int pos,int delta){ while(pos<=n)C[pos]+=delta, pos+=lowbit(pos); } int query(int x){ int sum=0; while(x>0){ sum+=C[x]; x-=lowbit(x); } return sum; } }T; int A[maxn],position[maxn]; int main(){ scanf("%d",&n); for(int i=1;i<=n;++i) scanf("%d",&A[i]), position[A[i]]=i; long long last=0; for(int i=n;i>=1;--i){ last+=T.query(A[i] -1); T.add(A[i],1); } long long best=last; for(int i=1;i<=n;++i) best=min(best,last-(position[i]-1) + (n-position[i])),last=last-(position[i]-1)+(n-position[i]); printf("%lld",best); return 0; }