题目描述
题解
ij的范围比较大,而n的范围只有
105
,直接离散化之后上ufs就好了。
将等于的情况先处理,不等于的情况后处理。
代码
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define N 100005
int T,n,cnt;
struct hp{int x,y,ty;}a[N];
int lsh[N*2],f[N*2];
void clear()
{
n=cnt=0;
}
int div(int x)
{
int l=1,r=cnt,mid,ans;
while (l<=r)
{
mid=(l+r)>>1;
if (lsh[mid]>=x) ans=mid,r=mid-1;
else l=mid+1;
}
return ans;
}
int cmp(hp a,hp b)
{
return a.ty>b.ty;
}
int find(int x)
{
if (x==f[x]) return x;
f[x]=find(f[x]);
return f[x];
}
int main()
{
scanf("%d",&T);
while (T--)
{
clear();
scanf("%d",&n);
for (int i=1;i<=n;++i)
{
scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].ty);
lsh[++cnt]=a[i].x,lsh[++cnt]=a[i].y;
}
sort(lsh+1,lsh+cnt+1);
cnt=unique(lsh+1,lsh+cnt+1)-lsh-1;
for (int i=1;i<=n;++i)
a[i].x=div(a[i].x),a[i].y=div(a[i].y);
for (int i=1;i<=cnt;++i) f[i]=i;
sort(a+1,a+n+1,cmp);bool flag=true;
for (int i=1;i<=n;++i)
{
int f1=find(a[i].x),f2=find(a[i].y);
if (a[i].ty==1)
{
if (f1!=f2) f[f1]=f2;
}
else
{
if (f1==f2)
{
flag=false;
break;
}
}
}
if (flag) puts("YES");
else puts("NO");
}
}
总结
①离散化的题目一定要细心一些。想好是离散化之前的还是之后的。