标签:des style blog http color io os ar for
Description
Input
Output
Sample Input
Sample Output
Memory: 320 KB | Time: 78 MS |
#include <cstdio> #include <iostream> 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); return ; } 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 res = sum; for(int i = 0;i < n;i++){ sum += n - x[i] - x[i] - 1; res = min(res,sum); } printf("%d\n",res); } return 0; }
后来我有用树状数组做了一下,发觉树状数组一般都要比线段树要快~
Memory: 332 KB | Time: 31 MS |
#include <cstdio> #include <iostream> #include <cstring> using namespace std; const int maxn = 5555; int c[maxn]; int a[maxn]; int n; inline int lowbit(int x){ return x&(-x); } int sum(int x){ int ret = 0; while(x > 0){ ret += c[x];x -= lowbit(x); } return ret; } void add(int x,int d){ while(x <= n){ c[x] += d;x += lowbit(x); } } int main(){ while(~scanf("%d",&n)){ memset(c,0,sizeof(c)); memset(a,0,sizeof(a)); int ans = 0; for(int i = 1;i <= n;i++){ scanf("%d",&a[i]); ans += i - 1 - sum(a[i]); add(a[i] + 1,1); } //cout<<ans<<endl; int MIN = ans; for(int i = 1;i <= n;i++){ MIN += n - (a[i] + 1) - (a[i]); ans = min(MIN,ans); } printf("%d\n",ans); } return 0; }
标签:des style blog http color io os ar for
原文地址:http://www.cnblogs.com/jusonalien/p/4004973.html