利用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 false;
if(color[v]==0 && !dfs(v,-c)) return false;
}
return true;
}
void solve() {
for(int i=0; i<n; ++i) { //如果是连通图,i==0时就可以遍历整张图
if(color[i]==0) {
if(!dfs(i,1)) {
printf("No\n");
return;
}
}
}
printf("Yes\n");
}