利用DFS
由于每个顶点和每条边都只访问了一次,因此
复杂度为O(V+E)
可用于检测是否存在奇环。
const int maxn = 1e4+10;
vector<int> g[maxn];
int n; //顶点数
int color[maxn]; //顶点i的颜色,1 or -1
bool dfs(int u, int c) {
color[u]=c;
for(int i=0; i<g[u].size(); ++i) {
int v=g[u][i];
if(color[v]==c) return 0;
if(color[v]==0&&!dfs(v,-c)) return 0;
}
return 1;
}
void solve() {
for(int i=1; i<=n; ++i) //如果是连通图,i==0时就可以遍历整张图
if(!color[i]&&!dfs(i,1)) { printf("No\n"); return; }
printf("Yes\n");
}