Dwarves line up
解题思路
用线段树维护每个人当前的位置的区间最大值和最小值,查询时若区间的长度和位置的最大值与最小值的差相对,则已经形成。
code
#include<iostream>
#include<cstdio>
using namespace std;
int n,m;
int a[200010];
struct abc{
int maxn,minn;
}tree[800010];
abc mix(abc a,abc b)
{
return (abc){max(a.maxn,b.maxn),min(a.minn,b.minn)};
}
void in(int num,int l,int r,int x,int a)
{
tree[num].maxn=max(tree[num].maxn,a);
tree[num].minn=min(tree[num].minn,a);
if(l==r)
return;
int mid=(l+r)/2;
if(x<=mid)
in(num*2,l,mid,x,a);
else
in(num*2+1,mid+1,r,x,a);
}
void chang(int num,int l,int r,int x,int a)
{
if(l==r)
{
tree[num]=(abc){a,a};
return;
}
int mid=(l+r)/2;
if(x<=mid)
chang(num*2,l,mid,x,a);
else
chang(num*2+1,mid+1,r,x,a);
tree[num].maxn=max(tree[num*2].maxn,tree[num*2+1].maxn);
tree[num].minn=min(tree[num*2].minn,tree[num*2+1].minn);
}
abc fd(int num,int l,int r,int a,int b)
{
if(l==a&&r==b)
return tree[num];
int mid=(l+r)/2;
if(b<=mid)
return fd(num*2,l,mid,a,b);
else if(a>mid)
return fd(num*2+1,mid+1,r,a,b);
else
return mix(fd(num*2,l,mid,a,mid),fd(num*2+1,mid+1,r,mid+1,b));
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n*4;i++) tree[i].minn=0x3f3f3f3f;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
in(1,1,n,a[i],i);
}
while(m--)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
if(x==1)
{
chang(1,1,n,a[z],y);
chang(1,1,n,a[y],z);
swap(a[z],a[y]);
}
else
{
abc t=fd(1,1,n,y,z);
if(t.maxn-t.minn==z-y)
printf("YES\n");
else
printf("NO\n");
}
}
}