这是我第一次用并查集解决问题,其实刷这道题就是为了学习并查集,这是学长在hdu上找的模板题
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 110000;
int par[N], mark[N];
int find1(int x)
{
int r = x;
while(par[r] != r) r = par[r];
int i = x, j;
while(i != r)
j = par[i], par[i] = r, i = j;
return r;
}
void unite(int x, int y)
{
x = find1(x);
y = find1(y);
par[x] = y;
}
bool same(int x, int y)
{
return find1(x) == find1(y);
}
int main()
{
while(true)
{
int a, b, min1 = 0x7fffffff, max1 = 0x80000000, f = 1, flag = 1, sum = 0;
for(int i = 0; i < N; i++)
par[i] = i, mark[i] = 0;
while(true)
{
scanf("%d%d", &a, &b); sum++;
if(a == -1)
{
f = 0; break;
}
if(a == 0) break;
min1 = (min1 < min(a, b)) ? min1 : min(a, b);
max1 = (max1 > max(a, b)) ? max1 : max(a, b);
mark[a] = mark[b] = 1;
if(same(a, b) == true) flag = 0;
else unite(a, b);
}
if(!f) break;
if(sum == 1 && a == 0) {printf("Yes\n"); continue;}
if(!flag) {printf("No\n"); continue;}
int cnt = 0;
for(int i = min1; i <= max1; i++)
if(mark[i] && par[i] == i) cnt++;
if(cnt == 1) printf("Yes\n");
else printf("No\n");
}
return 0;
}
标签:hdu,小希,int,1272,max1,par,mark,min1,find1
From: https://blog.51cto.com/u_4158567/6191063