题目传送门
一、二分图着色原理

二、dfs深度优先遍历解法
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
const int M = 1e5 * 2 + 10;
struct Edge {
int to, next;
} e[M];
int head[N], idx;
void add(int u, int v) {
e[++idx].to = v;
e[idx].next = head[u];
head[u] = idx;
}
int n, m, ans, ans1, ans2;
int color[N];
void dfs(int u, int c) {
if (c == 1) color[u] = 2, ans2++;
else if (c == 2) color[u] = 1, ans1++;
for (int i = head[u]; i; i = e[i].next) {
int v = e[i].to;
if (color[v] > 0) {
if (color[v] == color[u]) {
printf("Impossible");
exit(0);
}
}
else dfs(v, color[u]);
}
}
int main() {
cin >> n >> m;
int x, y;
for (int i = 1; i <= m; ++i) {
cin >> x >> y;
add(x, y), add(y, x);
}
for (int i = 1; i <= n; ++i)
if (!color[i]) {
ans1 = ans2 = 0;
dfs(i, 1);
ans += min(ans1, ans2);
}
printf("%d", ans);
return 0;
}
三、bfs广度优先遍历解法
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
const int M = 1e5 * 2 + 10;
int color[N];
int n, m, ans;
queue<int> q;
struct Edge {
int to, next;
} edge[M];
int idx, head[N];
void add(int u, int v) {
edge[++idx].to = v;
edge[idx].next = head[u];
head[u] = idx;
}
int bfs(int a) {
int ans1 = 0, ans2 = 0;
color[a] = 1;
ans1++;
q.push(a);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = head[u]; i; i = edge[i].next) {
int v = edge[i].to;
if (color[v] == 0) {
if (color[u] == 1) color[v] = 2, ans2++;
else if (color[u] == 2) color[v] = 1, ans1++;
q.push(v);
} else
if (color[v] == color[u]) {
printf("Impossible");
exit(0);
}
}
}
return min(ans1, ans2);
}
int main() {
cin >> n >> m;
for (int i = 1; i <= m; ++i) {
int x, y;
cin >> x >> y;
add(x, y), add(y, x);
}
for (int i = 1; i <= n; ++i)
if (!color[i]) ans += bfs(i);
printf("%d", ans);
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!