跳到正文

题解

题解:P16467 [GKS 2013 Practice] Bad Horse

blueV约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年5月16日
更新
2026年5月16日
篇幅
约 4 分钟
题目
P16467

版本

  1. v2当前
  2. v1

思路

这道题就是把每个成员看做图的一个顶点,把每个麻烦对(两人不能在同一部门)看做一条边,然后判断这张图是否为二分图。

为什么是二分图

题目要求的是,把所有人分成两个部门(两个集合),每个麻烦对中的两个人不能在同一个部门。这等价于每个麻烦对中的两个人必须分到不同的集合,这恰好与二分图的定义相同。

实现

判断是否为二分图,可以通过 DFS 或 BFS 进行二染色的方法来判断:

  • 任选一个未染色的顶点,染成颜色一。
  • 将其所有邻居染成相反颜色二。
  • 如果邻居已被染色且与颜色一相同,则不是二分图。
  • 重复直到所有顶点染色完毕就是二分图。
AC Code
C++
#include <bits/stdc++.h>

using namespace std;

bool check(const vector<vector<int>>& graph, int n) {
    vector<int> color(n, -1);
    for (int i = 0; i < n; i++) {
        if (color[i] == -1) {
            queue<int> q;
            q.push(i);
            color[i] = 0;
            while (!q.empty()) {
                int u = q.front(); q.pop();
                for (int v : graph[u]) {
                    if (color[v] == -1) {
                        color[v] = color[u] ^ 1;
                        q.push(v);
                    } else if (color[v] == color[u]) return false;
                }
            }
        }
    }
    return true;
}
int main() {
    int T;
    cin >> T;
    for (int t = 1; t <= T; t++) {
        int M;
        cin >> M;
        unordered_map<string, int> name;
        vector<pair<int, int>> edges;
        int n = 0;
        for (int i = 0; i < M; i++) {
            string a, b;
            cin >> a >> b;
            if (name.find(a) == name.end()) name[a] = n++;
            if (name.find(b) == name.end()) name[b] = n++;
            edges.push_back({name[a], name[b]});
        }
        vector<vector<int> > graph(n);
        for (auto& e : edges) {
            graph[e.first].push_back(e.second);
            graph[e.second].push_back(e.first);
        }
        bool ok = check(graph, n);
        cout << "Case #" << t << ": " << (ok ? "Yes" : "No") << endl;
    }

    return 0;
}
原文