求逆序对模板
方法一:离散化+树状数组
模板如下:
#include<iostream> #include<cstdio> #include <algorithm> using namespace std; const int MAXN=40001; int n, a[MAXN], tree[MAXN], tot; int lowbit(int x) { return x&-x; } int query(int x) { int ans=0; while (x>0) { ans+=tree[x]; x-=lowbit(x); } return ans; } void addz(int x) { while (x<=n) { tree[x]+=1; x+=lowbit(x); } return; } struct Node { int v, ord; bool operator < (const Node x) const { return v<x.v; } }node[MAXN]; int main() { scanf("%d", &n); for (int i=1; i<=n; i++) { scanf("%d", &node[i].v); node[i].ord=i; } sort(node+1, node+n+1 ); for (int i=1; i<=n; i++) a[node[i].ord]=i; for (int i=1; i<=n; i++) { addz(a[i]); tot+=i-query(a[i]); } printf("%d", tot); return 0; }
方法二:归并排序
模板如下:
#include<iostream> #include<cstdio> using namespace std; int n,A[40010],T[40010],num; void merge_sort(int x,int y){ if(y-x>1){ int mid=x+(y-x)/2; int p=x,q=mid,i=x; merge_sort(x,mid); merge_sort(mid,y); while(p<mid||q<y){ if(q>=y||(p<mid&&A[p]<=A[q])) T[i++]=A[p++]; else {T[i++]=A[q++];num+=mid-p;} } for(i=x;i<y;i++) A[i]=T[i]; } } int main(){ cin>>n; for(int i=1;i<=n;i++) scanf("%d",&A[i]); merge_sort(1,n+1); cout<<num<<endl; return 0; }