笔记
例题
题目
P1955 [NOI2015]程序自动分析
链接
(https://www.luogu.com.cn/problem/P1955)
分析
并查集+离散化
并查集find迭代70分,太坑了,得递归。
代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
const int maxn = 1e6 + 10;
int father[maxn],lsh[maxn*3];
struct node
{
long long a,b;
int e;
}arr[maxn];
bool cmp(node a,node b)
{
return a.e > b.e;
}
int findf(int x)
{
if(x==father[x])
return x;
else return father[x]=findf(father[x]);
}
int main()
{
int t,n;
scanf("%d",&t);
while(t--)
{
memset(lsh,0,sizeof(lsh));
memset(arr,0,sizeof(arr));
memset(father,0,sizeof(father));
scanf("%d",&n);
int k = 0;
for(int i = 1;i <= n;i++)
{
scanf("%lld%lld%d",&arr[i].a,&arr[i].b,&arr[i].e);
lsh[k++] = arr[i].a;
lsh[k++] = arr[i].b;
}
sort(lsh,lsh+k);
int num = unique(lsh,lsh+k)-lsh;
for(int i = 1;i <= n;i++)
{
arr[i].a = lower_bound(lsh,lsh+num,arr[i].a)-lsh;
arr[i].b = lower_bound(lsh,lsh+num,arr[i].b)-lsh;
}
sort(arr+1,arr+n+1,cmp);
for(int i = 1;i <= num;i++)
father[i] = i;
int flag = 1;
for(int i =1;i <= n;i++)
{
int fx = findf(arr[i].a);
int fy = findf(arr[i].b);
if(arr[i].e)
{
father[fx]=fy;
}
else if(fx == fy)
{
flag = 0;
break;
}
}
if(flag)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}