标签:line bsp 线段 build color update scan its print
题目链接:逆序数
模板题。
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 #define rep(i, a, b) for (int i(a); i <= (b); ++i) 6 #define lson i << 1, L, mid 7 #define rson i << 1 | 1, mid + 1, R 8 9 const int N = 100010; 10 11 long long ans = 0; 12 13 struct node{ 14 int x, y; 15 friend bool operator < (const node &a, const node &b){ 16 return a.x < b.x; 17 } 18 } a[N]; 19 20 int tree[N << 2]; 21 int c[N]; 22 int n; 23 24 inline void pushup(int i){ 25 tree[i] = tree[i << 1] + tree[i << 1 | 1]; 26 } 27 28 void build(int i, int L, int R){ 29 tree[i] = 0; 30 if (L == R) return ; 31 int mid = (L + R) >> 1; 32 build(lson); 33 build(rson); 34 } 35 36 void update(int i, int L, int R, int pos, int val){ 37 if (L == R && L == pos){ 38 tree[i] += val; 39 return; 40 } 41 42 int mid = (L + R) >> 1; 43 if (pos <= mid) update(lson, pos, val); 44 else update(rson, pos, val); 45 46 pushup(i); 47 } 48 49 int query(int i, int L, int R, int l, int r){ 50 if (L == l && R == r) return tree[i]; 51 int mid = (L + R) >> 1; 52 if (r <= mid) return query(lson, l, r); 53 else if (l > mid) return query(rson, l, r); 54 else return query(lson, l, mid) + query(rson, mid + 1, r); 55 } 56 57 int main(){ 58 59 scanf("%d", &n); 60 61 rep(i, 1, n){ 62 scanf("%d", &a[i].x); 63 a[i].y = i; 64 } 65 66 sort(a + 1, a + n + 1); 67 c[a[1].y] = 1; rep(i, 2, n) c[a[i].y] = a[i].x == a[i - 1].x ? c[a[i - 1].y] : c[a[i - 1].y] + 1; 68 69 build(1, 1, n); ans = 0; 70 71 rep(i, 1, n){ 72 ans += (long long)query(1, 1, n, min(c[i] + 1, n), n); 73 update(1, 1, n, c[i], 1); 74 } 75 76 printf("%lld\n", ans); 77 78 return 0; 79 }
标签:line bsp 线段 build color update scan its print
原文地址:http://www.cnblogs.com/cxhscst2/p/6607337.html