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|a−b|≤K, and unfriendly otherwise.
Given the orderings of fields on either side of the road through FJ’s farm, please count the number of unfriendly crossing pairs of breeds, where a crossing pair of breeds is defined as in the preceding problems.
题目大意就是,给两个1~N的排列,上下品种相同的连边,定义友好为品种的差值小于等于K,求所有不友好的交叉个数。
题解
CDQ分治。每个品种的牛有两个维度,第一维是他在第一行的位置,第二维是他在第二行的位置,先按第一维排序,然后cdq分治时对两个区间分别按第二维排序,显然有交叉要前面的第二维大于后面的第二维才可以。这样,有一个交叉就把他的品种加到树状数组里。统计答案的时候直接把品种符合不友好的累加就可以了。
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#define maxn 200006
#define lowbit(x) (x&-x)
#define LL long long
using namespace std;
inline char nc(){
static char buf[100000],*i=buf,*j=buf;
return i==j&&(j=(i=buf)+fread(buf,1,100000,stdin),i==j)?EOF:*i++;
}
inline int _read(){
char ch=getchar();int sum=0;
while(!(ch>='0'&&ch<='9')) ch=getchar();
while(ch>='0'&&ch<='9') sum=sum*10+ch-48,ch=getchar();
return sum;
}
struct data{
int x,p1,p2;
bool operator <(const data&b)const{return p2<b.p2;}
}a[maxn],c[maxn];
int n,K;
LL ans,f[maxn];
void put(int x){for(;x<=n;x+=lowbit(x)) f[x]++;}
LL get(int x){
LL sum=0;
for(;x;x-=lowbit(x)) sum+=f[x];
return sum;
}
void clear(int x){for(;x<=n+K;x+=lowbit(x)) f[x]=0;}
void cdq(int l,int r){
if(l>=r)return;
int mid=(l+r)>>1;
cdq(l,mid);cdq(mid+1,r);
int j=mid+1;
for(int i=l;i<=mid;i++){
while(j<=r&&a[j]<a[i])put(a[j++].x);
if(a[i].x>=K+1)ans+=get(a[i].x-K-1);
if(a[i].x+K<n)ans+=get(n)-get(a[i].x+K);
}
for(int i=l;i<=r;i++) clear(a[i].x);
for(int i=l;i<=r;i++)c[i]=a[i];
int i=l;j=mid+1;
for(int k=l;k<=r;k++) if(j>r||(i<=mid&&c[i]<c[j]))a[k]=c[i++];
else a[k]=c[j++];
}
bool cmp(data x,data y){return x.p1<y.p1;}
int main(){
freopen("friendcross.in","r",stdin);
freopen("friendcross.out","w",stdout);
n=_read();K=_read();
for(int i=1;i<=n;i++)a[_read()].p1=i,a[i].x=i;
for(int i=1;i<=n;i++)a[_read()].p2=i;
sort(a+1,a+1+n,cmp);
cdq(1,n);
printf("%lld",ans);
return 0;
}