2018 ICPC 北京区域赛 A - Jin Yong’s Wukong Ranking List(有向图判环)

传送门


题目大意

给出若干组 a    b a~~b a  b关系,代表 a > b a>b a>b,如果所有的大于关系都没问题那么输出 0 0 0,否则输出第一组出错误的两个人。

解题思路

第一眼确实会想到并查集,但是并查集并不好写,实际上如果我们把大于关系看做一条从 a → b a \rightarrow b ab的有向边,即如果出现非法情况显然是出现了环。

使用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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值