1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| #include <bits/stdc++.h> using namespace std; #define IOS ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define maxn 200005 #define ll long long int a[maxn]; ll b[maxn]; struct persistent_seg_tree { struct data { int sum; data() :sum(0) {} }; struct node { int l, r; data d; node() :l(0), r(0) {} }; vector<node> nodes; vector<int> roots; int sz;
void up(int id) { nodes[id].d.sum = nodes[nodes[id].l].d.sum + nodes[nodes[id].r].d.sum; } int newnode(int cpy) { int id = (int)nodes.size(); node tmp = nodes[cpy]; nodes.push_back(tmp); return id; } int add(int tp, int tl, int tr, int i, int v) { int id = newnode(tp); if (tl + 1 >= tr) { nodes[id].d.sum += v; return id; } int tmid = (tl + tr) / 2; if (i < tmid) { int nid = add(nodes[id].l, tl, tmid, i, v); nodes[id].l = nid; } else { int nid = add(nodes[id].r, tmid, tr, i, v); nodes[id].r = nid; } up(id); return id; } int getsum(int tp, int tl, int tr, int l, int r) { if (l <= tl && tr <= r) { return nodes[tp].d.sum; } int tmid = (tl + tr) / 2; int sum = 0; if (l < tmid) { sum += getsum(nodes[tp].l, tl, tmid, l, r); } if (r > tmid) { sum += getsum(nodes[tp].r, tmid, tr, l, r); } return sum; } void init(int range, int root_size) { sz = range; nodes.clear(); roots.clear(); nodes.reserve(root_size * (int)(log(sz * 2.0) / log(2.0) + 1.01)); nodes.push_back(node()); roots.reserve(root_size + 1); roots.push_back(0); } void add(int pos, int v) { int last = roots.back(); roots.push_back(add(last, 0, sz, pos, v)); } int getsum(int t, int l, int r) { if (t <= 0) return 0; if (r < l) return 0; if (t >= (int)roots.size()) t = (int)roots.size() - 1; return getsum(roots[t], 0, sz, l, r + 1); } }tree; signed main(){ IOS int n; cin>>n; ll tmp=n; int ma=-1; for (int i = 1; i <=n ; ++i) { cin>>b[i]; a[i]=min(b[i],tmp); ma=max(ma,a[i]); } tree.init(ma+1,4*n); for (int i = 1; i <=n ; ++i) { tree.add(a[i],1); } ll ans=0; for (int i = 1; i <=n ; ++i) { int r=min(n,a[i]); int l=i+1; if(r>=l)ans+=tree.getsum(r,i,n+1)-tree.getsum(l-1,i,n+1); } cout<<ans; return 0; }
|