Loading... # 染色法 ```cpp #include <bits/stdc++.h> using namespace std; const int N = 1e2 + 10, M = 2 * N; int h[N], e[M], ne[M], idx; int color[N]; int n, m; void add(int a, int b){ e[idx] = b, ne[idx] = h[a], h[a] = idx++; } bool dfs(int u, int c){ color[u] = c; for (int i = h[u]; ~i; i = ne[i]) { int j = e[i]; if (!color[j]) { if (!dfs(j, 3 - c)) return false; } else if (color[j] == c) return false; } return true; } int main(){ cin >> n >> m; int a, b; memset(h, -1, sizeof h); for (int i = 1; i <= m; i++) { cin >> a >> b; add(a, b), add(b, a); } bool flag = true; for (int i = 1; i <= n; i++) if (!color[i]) if (!dfs(i, 1)) flag = false; if (flag) cout << "YES" << endl; else cout << "NO" << endl; return 0; } ``` # 匈牙利算法 ```cpp #include <bits/stdc++.h> using namespace std; const int N = 500, M = 1e5 + 10; int h[N], e[M], ne[M], idx; int n1, n2, m; int match[N]; bool st[N]; void add(int a, int b){ ne[idx] = h[a], e[idx] = b, h[a] = idx++; } int find(int u){ for (int i = h[u]; ~i; i = ne[i]) { int j = e[i]; if (!st[j]) { st[j] = true; if (!match[j] || find(match[j])) { match[j] = u; return true; } } } return false; } int main(){ cin >> n1 >> n2 >> m; int a, b; for (int i = 0; i < m; i++) { cin >> a >> b; add(a, b); } int res = 0; for (int i = 1; i <= n1; i++) { memset(st, 0, sizeof st); if (find(i)) res++; } cout << res; return 0; } ``` Last modification:March 10, 2023 © Allow specification reprint Like 0 如果觉得我的文章对你有用,请随意赞赏
Comment here is closed