Input
Output
Sample Input
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0
#include<cstdio> #include<iostream> #include<cstring> #include<algorithm> #include<queue> #include<stack> #include<set> #include<vector> #include<map> const int maxn=5e5+5; typedef long long ll; using namespace std; struct node { ll l,r; ll sum; }tree[maxn<<2]; int a[maxn],sub[maxn],cnt; void pushup(int m) { tree[m].sum=(tree[m<<1].sum+tree[m<<1|1].sum); } //void pushdown(int m) //{ // if(tree[m].lazy) // { // tree[m<<1].lazy=tree[m].lazy; // tree[m<<1|1].lazy=tree[m].lazy; // tree[m<<1].sum=tree[m].lazy*(tree[m<<1].r-tree[m<<1].l+1); // tree[m<<1|1].sum=tree[m].lazy*(tree[m<<1|1].r-tree[m<<1|1].l+1); // tree[m].lazy=0; // } // return ; //} void build(int m,int l,int r) { tree[m].l=l; tree[m].r=r; tree[m].sum=0; if(l==r) { tree[m].sum=0; return ; } int mid=(tree[m].l+tree[m].r)>>1; build(m<<1,l,mid); build(m<<1|1,mid+1,r); pushup(m); return ; } void update(int m,int index ,int val) { if(tree[m].l==index&&tree[m].l==tree[m].r) { tree[m].sum++; return ; } int mid=(tree[m].l+tree[m].r)>>1; if(index<=mid) { update(m<<1,index,val); } else { update(m<<1|1,index,val); } pushup(m); return ; } ll query(int m,int l,int r) { if(l>r) { return 0; } if(tree[m].l==l&&tree[m].r==r) { return tree[m].sum; } // pushdown(m); int mid=(tree[m].l+tree[m].r)>>1; if(r<=mid) { return query(m<<1,l,r); } else if(l>mid) { return query(m<<1|1,l,r); } else { return query(m<<1,l,mid)+query(m<<1|1,mid+1,r); } } int main() { int n; while(cin>>n) { if(n==0) { break; } for(int i=0;i<n;++i)scanf("%d",&sub[i]),a[i]=sub[i]; sort(sub,sub+n); int size=unique(sub,sub+n)-sub; for(int i=0;i<n;i++) a[i]=lower_bound(sub,sub+size,a[i])-sub+1; build(1,1,size); ll sum=0; for(int t=0;t<n;t++) { sum+=query(1,a[t]+1,size); update(1,a[t],1); } printf("%lld\n",sum); } return 0; }
POJ-2299-Ultra-QuickSort(单点更新 + 区间查询+离散化)
原文:https://www.cnblogs.com/Staceyacm/p/11298857.html