[BZOJ]4991: [Usaco2017 Feb]Why Did the Cow Cross the Road III CDQ分治+树状数组

Description

Farmer John is continuing to ponder the issue of cows crossing the road through his farm, introduced in the preceding two problems. He realizes now that the threshold for friendliness is a bit more subtle than he previously considered – breeds aa and bb are now friendly if |a-b|≤K, and unfriendly otherwise.Given the orderings of fields on either side of the road through FJ’s farm, please count t
he number of unfriendly crossing pairs of breeds, where a crossing pair of breeds is defined as in the preceding problems.

题解:

首先题目大意:两列n的排列,相同的数连边,假如一对数的差>k且有交叉,ans++,求ans。对于每个数有三个属性,一个是在第一个序列中的位置,一个是在第二个序列中的位置,一个是它的值,就是个三维偏序问题,简单的CDQ分治,树套树空间过不去。

代码:

#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define pa pair<int,int>
const int Maxn=100010;
const int inf=2147483647;
int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
    return x*f;
}
int n,k,a[Maxn],b[Maxn],posa[Maxn],posb[Maxn];
struct Opt{int x,y,z;}q[Maxn],temp[Maxn];
bool cmp(Opt a,Opt b){return a.x>b.x;}
int s[Maxn];
void add(int x,int y){for(;x<=n;x+=(x&-x))s[x]+=y;}
int getsum(int x){int re=0;x=min(x,n);for(;x>0;x-=(x&-x))re+=s[x];return re;}
LL ans=0;
void solve(int l,int r)
{
    if(l==r)return;
    int mid=l+r>>1;
    solve(l,mid);solve(mid+1,r);
    int i=l,j=mid+1,len=0;
    while(i<=mid&&j<=r)
    {
        if(q[i].y<q[j].y)
        {
            add(q[i].z,1);
            temp[++len]=q[i++];
        }
        else
        {
            ans+=(LL)(getsum(q[j].z-k-1))+(LL)(getsum(n)-getsum(q[j].z+k));
            temp[++len]=q[j++];
        }
    }
    int t=i;
    while(i<=mid)temp[++len]=q[i++];
    while(j<=r)ans+=(LL)(getsum(q[j].z-k-1))+(LL)(getsum(n)-getsum(q[j].z+k)),temp[++len]=q[j++];
    for(int p=l;p<t;p++)add(q[p].z,-1);
    for(int p=1;p<=len;p++)q[p+l-1]=temp[p];
}
int main()
{
    n=read(),k=read();
    for(int i=1;i<=n;i++)a[i]=read(),posa[a[i]]=i;
    for(int i=1;i<=n;i++)b[i]=read(),posb[b[i]]=i;
    for(int i=1;i<=n;i++)q[i].x=posa[i],q[i].y=posb[i],q[i].z=i;
    sort(q+1,q+1+n,cmp);solve(1,n);
    printf("%lld",ans);
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值