求无向图的双连通分量,然后判断这个双连通分量是否存在奇环,实际上,我们可以反着想,如果一个连通分量是个二分图,那么就必然不存在奇环,所以,我们对于每一个二分图,判断它是否是二分图,如果是,就把它放到结果中即可。
至于判断奇环神马的模板,就是抄了抄佳哥的……其实上交的也不错……不过佳哥的我感觉更好一些
#include <cstdio>
#include <cstring>
#include <vector>
#include <stack>
using namespace std;
const int N = 1111;
int map[N][N], n, m, pre[N], iscut[N], bccno[N], dfs_clock, bcc_cnt;
int odd[N], col[N];
vector<int> G[N], bcc[N];
struct edge{
int u, v;
edge(int u, int v) : u(u), v(v){}
};
stack<edge> S;
int dfs(int u, int fa){
int lowu = pre[u] = ++dfs_clock;
int chd = 0;
for (int i = 0; i < G[u].size(); i++){
int v = G[u][i];
edge e = edge(u, v);
if (!pre[v]){
S.push(e);
chd += 1;
int lowv = dfs(v, u);
lowu = min(lowv, lowu);
if (lowv >= pre[u]){
iscut[u] = 1;
bcc_cnt += 1; bcc[bcc_cnt].clear();
for(; ;){
edge x = S.top(); S.pop();
if (bccno[x.u] != bcc_cnt){bcc[bcc_cnt].push_back(x.u); bccno[x.u] = bcc_cnt;}
if (bccno[x.v] != bcc_cnt){bcc[bcc_cnt].push_back(x.v); bccno[x.v] = bcc_cnt;}
if (x.u == u && x.v == v) break;
}
}
}
else if (pre[v] < pre[u] && v != fa){
S.push(e);
lowu = min(lowu, pre[v]);
}
}
if (fa < 0 && chd == 1) iscut[u] = 0;
return lowu;
}
void find_bcc(int n){
memset(pre, 0, sizeof(pre));
memset(iscut, 0, sizeof(iscut));
memset(bccno, 0, sizeof(bccno));
dfs_clock = bcc_cnt = 0;
for (int i = 0; i < n; i++)
if (!pre[i]) dfs(i, -1);
}
bool bipartite(int u, int b){
for (int i = 0; i < G[u].size(); i++){
int v = G[u][i]; if (bccno[v] != b) continue;
if (col[v] == col[u]) return 0;
if (!col[v]){
col[v] = 3 - col[u];
if (!bipartite(v, b)) return 0;
}
}
return 1;
}
int main(){
while(~scanf("%d%d", &n, &m)){
if (!n && !m) break;
int x, y;
memset(map, 0, sizeof(map));
for (int i = 0; i < n; i++)
G[i].clear();
for (int i = 0; i < m; i++){
scanf("%d%d", &x, &y);
x -= 1; y -= 1;
map[x][y] = map[y][x] = 1;
}
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (!map[i][j]){G[i].push_back(j); G[j].push_back(i);}
find_bcc(n);
memset(odd, 0, sizeof(odd));
for (int i = 1; i <= bcc_cnt; i++){
memset(col, 0, sizeof(col));
for (int j = 0; j < bcc[i].size(); j++)
bccno[bcc[i][j]] = i;
int u = bcc[i][0];
col[u] = 1;
if (!bipartite(u, i))
for (int j = 0; j < bcc[i].size(); j++) odd[bcc[i][j]] = 1;
}
int ans = n;
for (int i = 0; i < n; i++)
if (odd[i]) ans -= 1;
printf("%d\n", ans);
}
return 0;
}