题目大意
给出若干组 a b a~~b a b关系,代表 a > b a>b a>b,如果所有的大于关系都没问题那么输出 0 0 0,否则输出第一组出错误的两个人。
解题思路
第一眼确实会想到并查集,但是并查集并不好写,实际上如果我们把大于关系看做一条从 a → b a \rightarrow b a→b的有向边,即如果出现非法情况显然是出现了环。
使用bfs暴力判环即可,更推荐的做法是拓扑排序判环。
//
// Created by Happig on 2020/11/17
//
#include <bits/stdc++.h>
#include <unordered_map>
#include <unordered_set>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define ins insert
#define Vector Point
#define ENDL "\n"
#define lowbit(x) (x & (-x))
#define mkp(x, y) make_pair(x, y)
#define mem(a, x) memset(a, x, sizeof a);
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<double, double> pdd;
const double eps = 1e-8;
const double pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const double dinf = 1e300;
const ll INF = 1e18;
const int Mod = 1e9 + 7;
const int maxn = 2e5 + 10;
map<string, int> mp;
map<int, string> toStr;
bitset<maxn> vis;
int cnt, a[30], b[30];
void ID(string str) {
if (!mp.count(str)) {
mp[str] = ++cnt;
toStr[cnt] = str;
}
}
unordered_set<int> s[105];
bool bfs(int x, int y) {
queue<int> q;
vis.reset();
q.push(y);
while (!q.empty()) {
int u = q.front();
q.pop();
vis[u] = 1;
for (auto v : s[u]) {
if (!vis[v]) {
if (v == x) return 0;
q.push(v);
}
}
}
return 1;
}
int main() {
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
// ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int n;
string s1, s2;
while (cin >> n) {
cnt = 0;
mp.clear(), toStr.clear();
for (int i = 0; i < n; i++) {
cin >> s1 >> s2;
ID(s1), ID(s2);
a[i] = mp[s1], b[i] = mp[s2];
}
for (int i = 1; i <= 2 * n; i++) s[i].clear();
bool ok = 1;
for (int i = 0; i < n; i++) {
int x = a[i], y = b[i];
if (bfs(x, y)) {
s[x].insert(y);
} else {
ok = 0;
cout << toStr[x] << " " << toStr[y] << endl;
break;
}
}
if (ok) cout << "0" << endl;
}
return 0;
}