[51nod] 1019 逆序数
要点:左右分治
注解:使用了归并排序
空间复杂度:NlogN
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<cstdio> #include<iostream> using namespace std; int val[1000000] = {0}; int tmp[1000000] = {0}; int ans = 0; void mergesort(int L,int R){ if(L == R) return; mergesort(L,(L+R)/2); mergesort((L+R)/2+1,R); int p = L,lp = L,rp = (L+R)/2+1; while(p <= R){ if(lp > (L+R)/2) tmp[p++] = val[rp++]; else if(rp > R) tmp[p++] = val[lp++]; else if(val[lp] <= val[rp]) tmp[p++] = val[lp++]; else if(val[lp] > val[rp]) tmp[p++] = val[rp++],ans+=(L+R)/2-lp+1; } for(int i = L;i <= R;i++) val[i] = tmp[i]; } int main(){ int n; scanf("%d",&n); for(int i = 1;i <= n;i++) scanf("%d",&val[i]); if(n == 1) ans = 1; mergesort(1,n); printf("%d\n",ans); // for(int i = 1;i <= n;i++) printf("%d ",val[i]); return 0; }
转载请注明出处 -- 如有意见欢迎评论