题意:
分析:
//AC CODE(暴力):
#include<iostream> #include<cstdio> using namespace std; int sec[5010]; int main() { int n,i,j,sum,Min; while(scanf("%d",&n)!=EOF) { sum=0; for(i=0;i<n;i++) { scanf("%d",&sec[i]); for(j=i-1;j>=0;j--) { if(sec[j]>sec[i]) sum++; } } Min=sum; for(i=0;i<n-1;i++) { sum=sum-sec[i]+(n-1-sec[i]); if(Min>sum) Min=sum; } printf("%d\n",Min); } return 0; }
//AC CODE(线段树):http://www.notonlysuccess.com/?p=978
线段树能用到这种境界~ 膜拜!
#include <cstdio> #include <algorithm> using namespace std; #define lson l , m , rt << 1 #define rson m + 1 , r , rt << 1 | 1 const int maxn = 5555; int sum[maxn<<2]; void PushUP(int rt) { sum[rt] = sum[rt<<1] + sum[rt<<1|1]; } void build(int l,int r,int rt) { sum[rt] = 0; if (l == r) return ; int m = (l + r) >> 1; build(lson); build(rson); } void update(int p,int l,int r,int rt) { if (l == r) { sum[rt] ++; return ; } int m = (l + r) >> 1; if (p <= m) update(p , lson); else update(p , rson); PushUP(rt); } int query(int L,int R,int l,int r,int rt) { if (L <= l && r <= R) { return sum[rt]; } int m = (l + r) >> 1; int ret = 0; if (L <= m) ret += query(L , R , lson); if (R > m) ret += query(L , R , rson); return ret; } int x[maxn]; int main() { int n; while (~scanf("%d",&n)) { build(0 , n - 1 , 1); int sum = 0; for (int i = 0 ; i < n ; i ++) { scanf("%d",&x[i]); sum += query(x[i] , n - 1 , 0 , n - 1 , 1); update(x[i] , 0 , n - 1 , 1); } int ret = sum; for (int i = 0 ; i < n ; i ++) { sum += n - x[i] - x[i] - 1; ret = min(ret , sum); } printf("%d\n",ret); } return 0; }