归并排序求逆序数

学习归并排序时看了:https://blog.youkuaiyun.com/yuehailin/article/details/68961304,写的挺好的,推荐大家看下。

归并排序模板

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <set>

using namespace std;
typedef long long ll;
const ll mod=998244353;
const ll maxn=500005;

int A[maxn<<2];

void mergearray(int *a,int l,int r) {
    int *temp=new int [r-l+1];
    int mid=(l+r)>>1;
    int i=l,j=mid+1,k=0;
    while(i<=mid&&j<=r) {
        temp[k++]=a[i]<=a[j]?a[i++]:a[j++];
    }

    while(i<=mid)temp[k++]=a[i++];

    while(j<=r)temp[k++]=a[j++];

    for(int c=0;c<k;c++)a[l+c]=temp[c];
}

void mergesort(int *a,int l,int r) {
    if(l<r) {
        int mid=(l+r)>>1;
        mergesort(a,l,mid);
        mergesort(a,mid+1,r);

        mergearray(a,l,r);
    }
}

void print(int n) {
    for(int i=1;i<=n;i++)
        cout<<A[i]<<" ";
    cout<<endl;
}

int main () {
    ios::sync_with_stdio(false);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)cin>>A[i];
    mergesort(A,1,n);
    print(n);
    return 0;
}

 

归并排序求逆序数(POJ 2299)

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <set>

using namespace std;
typedef long long ll;
const ll mod=998244353;
const ll maxn=500005;
int A[maxn<<2];
ll n,ans;
void mergearray(int *a,ll l,ll r) {
    int *temp=new int [r-l+1];
    int mid=(l+r)/2;
    ll i=l,j=mid+1,k=0;

    while(i<=mid&&j<=r) {
        if(a[i]<=a[j])
            temp[k++]=a[i++];

        else {
            temp[k++]=a[j++];
            ans+=mid-i+1;
        }
    }
    while(i<=mid)temp[k++]=a[i++];

    while(j<=r)temp[k++]=a[j++];

    for(ll c=0;c<k;c++)
        a[l+c]=temp[c];
}

void mergesort(int *a,ll l,ll r) {
    if(l<r) {
        int mid=(l+r)/2;
        mergesort(a,l,mid);
        mergesort(a,mid+1,r);
        mergearray(a,l,r);
    }
}

void print(ll n) {
    for(ll i=1;i<=n;i++)
        cout<<A[i]<<" ";
    cout<<endl;
}

int main () {
    ios::sync_with_stdio(false);
    while(cin>>n&&n) {
        for(ll i=1;i<=n;i++)
            cin>>A[i];
        ans=0;
        mergesort(A,1,n);
        //print(n);
        cout<<ans<<endl;
    }
    return 0;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水能zai舟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值