题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=42
先用并查集判断图是否连通,如果不连通,直接输出No
如果连通,判断奇数度的顶点的个数是否为0或者2,如果是,输出Yes,反之,输出No
代码:
#include <cstdio>
#include <cstring>
using namespace std;
int n;
int p,q;
int a,b;
int f[1005];
int degree[1005];
int findIt(int x)
{
return f[x] == x ? x : f[x] = findIt(f[x]);
}
int main()
{
int n;
while(~scanf("%d",&n))
{
while(n--)
{
memset(degree,0,sizeof degree);
scanf("%d%d",&p,&q);
for(int i = 1; i <= p; ++i)
f[i] = i;
for(int i = 1; i <= q; ++i)
{
scanf("%d%d",&a,&b);
degree[a]++;
degree[b]++;
int ta = findIt(a);
int tb = findIt(b);
if(ta != tb)
{
f[ta] = tb;
}
}
int cnt = 0;
for(int i = 1; i <= p; ++i)
if(f[i] == i)
cnt++;
//printf("cnt = %d\n",cnt);
if(cnt != 1)
printf("No\n");
else
{
int cnt1 = 0;
for(int i = 1; i <= p; ++i)
if(degree[i] % 2)
cnt1++;
//printf("cnt1 = %d\n",cnt1);
if(cnt1 == 0 || cnt1 == 2)
printf("Yes\n");
else
printf("No\n");
}
}
}
return 0;
}