樹狀陣列求逆序對
阿新 • • 發佈:2021-08-12
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; int sum,tree[300005],ll[300005],rank[300005],n; struct Node{ int num,val; }a[300005]; int lowbit(int x){ return (-x)&x; } int cmp(Node q,Node w){ if(q.val==w.val) return q.num<w.num; return q.val<w.val; }int add(int ip,int k){ for(int i=ip;i<=n;i+=lowbit(i)) tree[i]+=k; return 0; } int query(int ip){ int ans=0; for(int i=ip;i>0;i-=lowbit(i)) ans+=tree[i]; return ans; } int main(){ scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&a[i].val); a[i].num=i; } sort(a+1,a+1+n,cmp); for(int i=1;i<=n;i++) rank[a[i].num]=i; for(int i=1;i<=n;i++){ add(rank[i],1); sum+=i-query(rank[i]); //ll[i]=i-query(rank[i]); ① } cout<<sum; //for(int i=1;i<=n;i++) cout<<ll[i]<<" "; ② return0; }
如果加了①②就可以求前k箇中第k位數是第幾大了