二分图 50 求助
查看原帖
二分图 50 求助
374769
Epi4any楼主2023/1/1 22:31
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int maxn = 1e5 + 10;
int n, m, head[maxn], tot, color[maxn], vis[maxn], cnt[maxn];
struct Edge {
	int v, to;
} e[maxn << 1];
inline void addedge(int u, int v) {
	e[++tot] = {v, head[u]};
	head[u] = tot;
}
bool dfs(int u, bool c) {
	color[u] = c, vis[u] = true, cnt[c]++;
	for (int i = head[u]; i; i = e[i].to) {
		int v = e[i].v;
		if (vis[v]) {
			if (color[u] == color[v]) return false;
			continue;
		}
		if (!dfs(v, c == 0)) return false;
	}
	return true;
}
signed main() {
	cin >> n >> m;
	for (int i = 1, u, v; i <= m; i++) {
		cin >> u >> v;
		addedge(u, v), addedge(v, u);
	}
	for (int i = 1; i <= n; i++) {
		if (vis[i]) continue;
		if (dfs(i, 0) == false) {
			cout << "Impossible" << endl;
			return 0;
		}
	}
	cout<<min(cnt[0],cnt[1])<<endl;
	return 0;
}
2023/1/1 22:31
加载中...