【求逆序对】CODE[VS] 3286 火柴排队 (树状数组离散化求逆序对)

点击火柴一键排队


逆序对,听起来高大上,实际上就是逆序的数对233333
可以用归并排序的性质求解
但是我们也可以用树状数组+离散化很方便地求出

额,你问我什么是离散化?。。。。

离散化通常就是将范围很广的一段数据映射到范围较窄的一段数据上
通常可以选择直接存地址(数组下标),或者%一个数(常为大质数)存余数

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define mod 99999997

const int maxn = 200005;

using namespace std;
typedef long long LL;

LL n;
LL ans;
LL c[maxn];
LL hah[maxn];

struct node 
{
    LL v,xh;
}a[maxn],b[maxn];

int lowbit(int x)
{
    return x&(-x);
}

bool cmp(node ax,node bx)
{
    return ax.v < bx.v;
}

bool cmp2(node ax,node bx)
{
    return ax.xh < bx.xh;
}

inline LL read()
{
    char ch;
    LL f = 1;
    LL data = 0;
    while(ch < '0'|| ch > '9')
    {
        ch = getchar();
        if(ch == '-')
            f = -1;
    }
    do{
        data = data*10 + ch-'0';
        ch = getchar();
    }while(ch >= '0'&&ch <= '9');

return data*f;
}

inline void add(LL i,LL num)
{
    while(i <= n)
    {
        c[i] += num;
        i += lowbit(i);
    }
}

inline LL sum(LL x)
{
    LL cnt = 0;
    while(x > 0)
    {
        cnt += c[x];
        x -= lowbit(x);
    }
    return cnt;
}

int main()
{
    //readin
    n = read();
    for(LL i = 1;i <= n;i++){ a[i].v = read(); a[i].xh = i;}
    for(LL i = 1;i <= n;i++){ b[i].v = read(); b[i].xh = i;}
    //hash
    sort(a+1,a+n+1,cmp);
    sort(b+1,b+n+1,cmp);//按照数值大小排序
    for(LL i = 1;i <= n;i++)
    {
        hah[a[i].xh] = b[i].xh;//离散化操作
    }
    //ask
    sort(a+1,a+n+1,cmp2);
    for(LL i = 1;i <= n;i++)
    {
        add(hah[i],1);
        ans = (ans + i-sum(hah[i]))%mod;
    }
    printf("%lld\n",ans);
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值