一、离散化:
https://www.cnblogs.com/2018zxy/p/10104393.html
二、逆序数
AC代码:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; typedef long long LL; const int maxn = 510000; struct Node{ LL data; int val; }cur[maxn]; LL a[maxn]; bool cmp(Node A,Node B) { return A.data<B.data; } int lowbit(int x) { return x&(-x); } void update(int x) { while(x<maxn-10) { a[x]++; x+=lowbit(x); } } int sum(int x) { int ans=0; while(x>0) { ans+=a[x]; x-=lowbit(x); } return ans; } int main(void) { int n,i; while(~scanf("%d",&n)&&n) { memset(a,0,sizeof(a)); for(i=1;i<=n;i++) { scanf("%lld",&cur[i].data);cur[i].val=i; } sort(cur+1,cur+1+n,cmp); LL ans=0; for(i=1;i<=n;i++) { update(cur[i].val); ans+=i-sum(cur[i].val); } printf("%lld\n",ans); } return 0; }
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; typedef long long LL; const int maxn = 510000; struct Node{ LL data; int val; }cur[maxn]; LL a[maxn]; bool cmp(Node A,Node B) { return A.data<B.data; } int lowbit(int x) { return x&(-x); } void update(int x) { while(x<maxn-10) { a[x]++; x+=lowbit(x); } } int sum(int x) { int ans=0; while(x>0) { ans+=a[x]; x-=lowbit(x); } return ans; } int main(void) { int n,i; while(~scanf("%d",&n)&&n) { memset(a,0,sizeof(a)); for(i=1;i<=n;i++) { scanf("%lld",&cur[i].data);cur[i].val=i; } sort(cur+1,cur+1+n,cmp); LL ans=0; for(i=n;i>=1;i--) { ans+=sum(cur[i].val); update(cur[i].val); } printf("%lld\n",ans); } return 0; }