一个无向图,问有没有奇偶环。
注意这里如果两个奇环仅共点,合起来算偶环。。敲了一个染色的做法,因为染色的时候,只可能遗漏偶环(由奇环拼成的偶环),因此我们每次找到奇环,给环上的点打标记,如果有点被打了两次标记,说明存在偶环。
//#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:102400000,102400000")
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
#define ll long long
const int maxn = 100010;
const int maxm = 300010;
int head[maxn];
int pre[maxm<<1];
int to[maxm<<1];
int tot;
int n,m;
int cnt[maxn];
int color[maxn];
int fa[maxn];
bool ji;
bool ou;
void init(){
tot=0;
memset(head,-1,sizeof(head));
memset(cnt,0,sizeof(cnt));
memset(color,-1,sizeof(color));
memset(fa,-1,sizeof(fa));
ji=0; ou=0;
}
void addedge(int u,int v){
to[tot]=v;
pre[tot]=head[u];
head[u]=tot++;
//
to[tot]=u;
pre[tot]=head[v];
head[v]=tot++;
}
void dfs(int u){
for(int i=head[u];i!=-1;i=pre[i]){
int v=to[i];
if(v==fa[u])continue;
if(color[v]==-1){
color[v]=!color[u];
fa[v]=u;
dfs(v);
}else{
if(color[u]==color[v]){ //奇环
ji=1;
int cur=u;
while(cur!=v){
if(cur==-1)break;
cnt[cur]++;
if(cnt[cur]>1)ou=1;
cur=fa[cur];
}
}else{ //偶环
ou=1;
}
}
}
}
int main(){
int t;
cin>>t;
while(t--){
init();
cin>>n>>m;
for(int i=1;i<=m;i++){
int u,v;
scanf("%d%d",&u,&v);
addedge(u,v);
}
for(int i=1;i<=n;i++){
if(color[i]==-1){
color[i]=0;
dfs(i);
}
}
if(ji){
cout<<"YES"<<endl;
}else{
cout<<"NO"<<endl;
}
if(ou){
cout<<"YES"<<endl;
}else{
cout<<"NO"<<endl;
}
}
return 0;
}
另外这个题可以用tarjan判偶环。我们使用tarjan求出所有双连通分量,在一个连通分量内,肯定是有环的。只有一种情况不存在偶环,就是这个双连通是一个纯的奇环。。