归并排序求逆序数

归并排序求逆序数

理解原理,这样才可以灵活运用

【时间复杂度】(O(nlogn))

&代码:

#include <cstdio>
#include <bitset>
#include <iostream>
#include <set>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
using namespace std;
#define INF 0x3f3f3f3f
#define DG(x) cout<<#x<<"="<<(x)<<'
';
#define DGG(x,y) cout<<#x<<"="<<(x)<<" "<<#y<<"="<<(y)<<'
';
#define DGGG(x,y,z) cout<<#x<<"="<<(x)<<" "<<#y<<"="<<(y)<<" "<<#z<<"="<<(z)<<'
';
typedef long long ll;
const int maxn= 1e6 +7;
int t,a[maxn],z[maxn];
//逆序数的答案必须是ll  因为会爆int
ll cnt;
void merge_sort(int* A,int x,int y,int* T)
{
    if(y-x>1){
        int m=x+(y-x)/2;
        merge_sort(A,x,m,T);
        merge_sort(A,m,y,T);
        int p=x,q=m,i=x;
        while(p<m||q<y){
            if(q>=y||(p<m&&A[p]<=A[q])) T[i++]=A[p++];
            //只是在归并排序上加了cnt+=m-p 就可以求逆序数了
            else T[i++]=A[q++],cnt+=m-p;
        }
        for(i=x;i<y;i++) A[i]=T[i];
    }
}
int main() {
    freopen("E:1.in","r",stdin);
    while(cin>>t){
        for(int i=0;i<t;i++){
            cin>>a[i];
        }
        cnt=0;
        merge_sort(a,0,t,z);
        cout<<cnt<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/s1124yy/p/6687693.html