【51NOD-0】1019 逆序数
【算法】离散化+树状数组(求逆序对)
【题解】经典,原理是统计在i之前插入的且值≤i的个数,然后答案就是i-getsum(i)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<cstdio> #include<algorithm> #include<cstring> #define lowbit(x) x&(-x) using namespace std; const int maxn=50010; int A[maxn],ord[maxn],a[maxn],b[maxn],n,s; bool cmp(int x,int y) {return a[x]<a[y];} void insert(int x) { for(int i=x;i<=s;i+=lowbit(i))A[i]++; } int getsum(int x) { int ans=0; for(int i=x;i>=1;i-=lowbit(i))ans+=A[i]; return ans; } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&a[i]); ord[i]=i; } sort(ord+1,ord+n+1,cmp); s=1;b[ord[1]]=1; for(int i=2;i<=n;i++)b[ord[i]]=a[ord[i]]==a[ord[i-1]]?s:++s; int ans=0; for(int i=1;i<=n;i++) { insert(b[i]); ans+=i-getsum(b[i]); } printf("%d",ans); return 0; }