• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ACM s1124yy
守りたいものが 強くさせること
博客园    首页    新随笔    联系   管理     

归并排序求逆序数

归并排序求逆序数

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

【时间复杂度】\(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)<<'\n';
#define DGG(x,y) cout<<#x<<"="<<(x)<<" "<<#y<<"="<<(y)<<'\n';
#define DGGG(x,y,z) cout<<#x<<"="<<(x)<<" "<<#y<<"="<<(y)<<" "<<#z<<"="<<(z)<<'\n';
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;
}
posted @ 2017-04-10 10:04  s1124yy  阅读(138)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3