标签:sam pair script cas stream update query 遍历 lines
1 #include <iostream> 2 #include <cstdio> 3 #define lson l, m, rt<<1 4 #define rson m+1, r, rt<<1|1 5 using namespace std; 6 const int maxn = 5e3+10; 7 8 int min(int a, int b){ 9 return a>b?b:a; 10 } 11 int sum[maxn<<2], a[maxn]; 12 void PushUP(int rt){ 13 sum[rt] = sum[rt<<1] + sum[rt<<1|1]; 14 } 15 void build(int l, int r, int rt){ 16 sum[rt] = 0; 17 if(l == r)return; 18 int m = (l + r) >> 1; 19 build(lson); 20 build(rson); 21 } 22 int query(int L, int R, int l, int r, int rt){ 23 if(L <= l && r <= R){ 24 return sum[rt]; 25 } 26 int m = (l + r) >> 1; 27 int ans = 0; 28 if(m >= L) ans +=query(L, R, lson); 29 if(m < R) ans += query(L, R, rson); 30 return ans; 31 } 32 void update(int p, int l, int r, int rt){ 33 if(l == r){ 34 sum[rt]++; 35 return; 36 } 37 int m = (l + r) >> 1; 38 if(p <= m) update(p,lson); 39 else update(p,rson); 40 PushUP(rt); 41 } 42 int main(){ 43 int n; 44 while(cin>>n){ 45 int sn = 0; 46 build(0, n - 1, 1); 47 for(int i = 0; i < n; i++){ 48 scanf("%d",&a[i]); 49 sn += query(a[i], n - 1, 0, n -1, 1); 50 update(a[i], 0, n - 1, 1); 51 } 52 int ans = sn; 53 for(int i = 0; i < n; i++){ 54 sn = sn - a[i] + n - a[i] - 1; 55 if(sn < ans){ 56 ans = sn; 57 } 58 } 59 cout << ans << endl; 60 } 61 return 0; 62 }
暴力代码:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 int a[5005],b[5005]; 6 int main(){ 7 int n; 8 while(cin>>n){ 9 memset(a, 0, sizeof(a)); 10 memset(b, 0, sizeof(b)); 11 for(int i = 0; i < n; i++){ 12 scanf("%d",&a[i]); 13 } 14 int sum = 0; 15 for(int i = 0; i < n; i++){ 16 for(int j = i+1; j < n; j++){ 17 if(a[i] > a[j]){ 18 b[i]++; 19 } 20 } 21 sum += b[i]; 22 } 23 int minx = sum; 24 for(int i = 0; i < n; i++){ 25 sum = sum - a[i] + (n - a[i] - 1); 26 if(sum < minx){ 27 minx = sum; 28 } 29 } 30 cout << minx << endl; 31 } 32 return 0; 33 }
标签:sam pair script cas stream update query 遍历 lines
原文地址:http://www.cnblogs.com/xingkongyihao/p/6533576.html