可以发现如果存在只有一个点的联通块,那么一定是不合法的。而其他的情况都存在合法方案。
(但是我感觉考场上蒟蒻不会推并不敢这样写啊)
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n,m,cnt,now;
int head[200005],next[1000005],list[1000005];
bool v[200005];
inline int read()
{
int a=0,f=1; char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1; c=getchar();}
while (c>='0'&&c<='9') {a=a*10+c-'0'; c=getchar();}
return a*f;
}
inline void insert(int x,int y)
{
next[++cnt]=head[x];
head[x]=cnt;
list[cnt]=y;
}
void dfs(int x)
{
v[x]=1; now++;
for (int i=head[x];i;i=next[i])
if (!v[list[i]]) dfs(list[i]);
}
int main()
{
n=read(); m=read();
for (int i=1;i<=m;i++)
{
int u=read(),v=read();
insert(u,v); insert(v,u);
}
for (int i=1;i<=n;i++)
if (!v[i])
{
now=0;
dfs(i);
if (now==1) {puts("NIE"); return 0;}
}
puts("TAK");
return 0;
}
本文介绍了一种通过深度优先搜索(DFS)判断无向图中是否存在仅包含单一顶点的联通块的方法,并给出完整的C++代码实现。文章指出,若存在这样的联通块,则该图不合法;反之则存在合法方案。此算法适用于竞赛编程等场景。
335

被折叠的 条评论
为什么被折叠?



