【每日一题】34. 图的遍历 (连通图,二分图)

补题链接:Here

算法涉及:连通图,二分图,图的存储与遍历

这个图必须要连通的,其次要有个奇环
对于不连通的图,只需要加上 连通块数量-1 的边即可将它变成连通
对于不存在奇环的,可以在连通的图上加一条边生成一个奇环
所以 (DFS) 每个连通块,在 (DFS) 过程中顺便用染色法判定下这是不是个二分图
因为二分图不含奇环,如果它是二分图就说明它有奇环
最后答案就是 连通快的数量 - (有无奇环)

const int N = 1e5 + 10;
int n, m, odd, x, y, res, vis[N], color[N];
vector<int> g[N];
void dfs(int u) {
	for (auto v : g[u]) {
		if (!vis[v]) {
			vis[v] = 1;
			color[v] = !color[u];
			dfs(v);
		} else if (color[u] == color[v])
			odd = 1;
	}
}
void solve() {
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		cin >> x >> y;
		g[x].push_back(y);
		g[y].push_back(x);
	}
	for (int i = 1; i <= n; i++) {
		if (!vis[i]) {
			res++;
			vis[i] = color[i] = 1;
			dfs(i);
		}
	}
	cout << res - odd << '
';
}

The desire of his soul is the prophecy of his fate
你灵魂的欲望,是你命运的先知。

原文地址:https://www.cnblogs.com/RioTian/p/14810267.html