NOIP2013提高组 火柴排队 (逆序对+特殊映射)

该博客探讨了NOIP2013提高组竞赛中的一道题目,涉及如何将两个数组的第i大元素配对,通过计算逆序对数量来确定需要交换的次数。博主使用C++编程实现,通过二分查找算法求解逆序对问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

这道题题目十分吓人,但其实就是要将两个数组中第i大的排在一起就好了。
所以我们的问题就变成了变成上述情况要交换多少次。
这里我的方法是:用c[i];来表示b中i这个位置的数需要匹配的a中数的位置。(a数组不动)。
这样仔细一想就会发现次数其实就是c中的逆序对数。
然后就是用二分求逆序对了。
详细代码如下:

#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn=100005;
const int mod=99999997;
struct shu
{
    int w,id;
    friend bool operator <(shu a,shu b)
    {
        return a.w<b.w;
    } 
}a[maxn],b[maxn];
int n,c[maxn],t[maxn];

int read()
{
    int x=0,ok=0;
    char ch;
    ch=getchar();

    while((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
    while((ch>='0'&&ch<='9')||ch=='-')
    {
        if(ch=='-') ok=1;
        else x=x*10+ch-'0';
        ch=getchar();
    }

    return ok==1?-x:x;
}

void init()
{
    n=read();
    for(int i=1;i<=n;i++)
    {
        a[i].w=read();
        a[i].id=i;
    }
    sort(a+1,a+1+n);
    for(int i=1;i<=n;i++)
    {
        b[i].w=read();
        b[i].id=i;
    }
    sort(b+1,b+1+n);
    for(int i=1;i<=n;i++)
    c[b[i].id]=a[i].id;//映射。
}
long long run(int x,int y)//求逆序对。
{
    if(x>=y) return 0;
    int m=x+y>>1;
    long long t1=0,t2=0,t3=0;
    t1=run(x,m);
    t2=run(m+1,y);
    int i=x,j=m+1,k=x;
    while(i<=m&&j<=y)
    {
        if(c[i]>c[j])
        {
        t[k++]=c[j++];
        t3=(t3+m-i+1)%mod;
        }
        else t[k++]=c[i++];
    }
    while(i<=m) t[k++]=c[i++];
    while(j<=y) t[k++]=c[j++];
    for(int i=x;i<=y;i++)
       c[i]=t[i];
    return (t1+t2+t3)%mod;
}

int main()
{
    //freopen("match.in","r",stdin);
    init();
    long long ans=run(1,n);
    cout<<ans;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值