题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3478
解题思路:题目的意思可以理解为能否存在这样一个步数,使得刚好花费这些步数可以到达所有的点。
那么我们可以把步数假设为无限大。
假设这个步数为偶数(用奇数考虑也可以),那么所有偶数步可以到的点一定能到,对吧。
那么奇数步的点怎样才能到呢,我们需要经过奇数步后,到达原先的偶数点。
怎样才行?只要你有一个奇数环,你通过这个环一圈回到原点就是用奇数步到达了一个偶数步点!
于是问题转化为了问该图中有无奇数环?
想到了二分图的性质:没有奇数环。
于是通过dfs染色来判断是否为二分图。
有关这个不了解的,也许可以看一下这篇里面的讲解。https://blog.youkuaiyun.com/weixin_43768644/article/details/89930796
代码:
#include<cstdio>
#include<cstring>
const int N = 1e5+5;
const int M = 5e5+5;
struct node{
int to,last;
}edge[M<<1];
int head[N],id,col[N];
bool flag;
void add(int u,int v){edge[id].to = v;edge[id].last = head[u];head[u] = id++;}
void dfs(int now,int pre,int color)
{
if (col[now] && col[now]!=color){
flag = false;
return ;
}
if (!flag) return ;
if (col[now]) return ;
col[now] = color;
color = (color==1)? 2:1;
for (int i=head[now];i!=0;i=edge[i].last){
if (edge[i].to!=pre){
dfs(edge[i].to,now,color);
}
}
}
int main()
{
int T;
scanf("%d",&T);
for (int sb=1;sb<=T;sb++){
int n,m,s;
scanf("%d %d %d",&n,&m,&s);
for (int i=1;i<=n;i++) head[i] = col[i] = 0;
id = 1;
while (m--){
int u,v;
scanf("%d %d",&u,&v);
u++,v++;
add(u,v);
add(v,u);
}
flag = true;
dfs(s+1,s+1,1);
printf("Case %d: %s\n",sb,flag?"NO":"YES");
}
return 0;
}