传递闭包模板

Tips:用于解决A<B,B<C等不等式传递问题(也可以用拓扑排序解决)

#include<bits/stdc++.h>
#include <ostream>

using namespace std;
typedef long long ll;
//#define endl '\n'
typedef pair<int, int> PII;
#define debug() cout.flush()
#define for0(i, a) for (int i = 0; i < a; ++i)
#define REP(i, a, b)  for (int i = a; i < b; ++i)
#define FOR(i, a, b)  for (int i = a; i <= b; ++i)
#define REPC(i, a, b, c)  for (ll i = a; i < b && i < c; ++i)
#define RREP(i, a, b) for (int i = a; i >= b; --i)
const ll MOD = 1e9 + 7;
const ll mod = 998244353;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e6 + 5e3;

inline void init() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
}

int n, m, l, r, type, dist[30][30], vis[30];

inline void floyd() {
    for (int i = 0; i < n; i++) {
        if (dist[i][l]) dist[i][r] = 1;
        if (dist[r][i]) dist[l][i] = 1;
        for (int j = 0; j < n; j++) {
            if (dist[i][l] && dist[r][j]) {
                dist[i][j] = 1;
            }
        }
    }
}

inline int check() {
    for (int i = 0; i < n; i++) if (dist[i][i]) return 2; //冲突
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < i; j++) {
            if (!dist[i][j] && !dist[j][i]) return 0; //关系无法确定
        }
    }
    return 1; //关系确定完成
}

inline char getMin() {
    for (int i = 0; i < n; i++) {
        if (!vis[i]) {
            int cnt = 0;
            for (int j = 0; j < n; j++) {
                if (!vis[j] && dist[j][i]) {
                    cnt++;
                    break;
                }
            }
            if (!cnt) {
                vis[i] = 1;
                return 'A' + i;
            }
        }

    }
}

inline void solve() {
    type = 0;
    memset(dist, 0, sizeof(dist));
    memset(vis, 0, sizeof(vis));
    int res;
    for (int i = 1; i <= m; i++) {
        string s;
        cin >> s;
        l = s[0] - 'A';
        r = s[2] - 'A';
        if (!type) {
            dist[l][r] = 1;
            floyd();
            type = check();
            if (type) {
                res = i;
            }
        }
    }
    if (!type) {
        cout << "Sorted sequence cannot be determined." << endl;
    } else if (type == 1) {
        cout << "Sorted sequence determined after " << res << " relations: ";
        for (int i = 0; i < n; i++) {
            cout << getMin();
        }
        cout << '.' << endl;
    } else {
        cout << "Inconsistency found after " << res << " relations." << endl;
    }
}

signed main() {
    init();
    while (cin >> n >> m){
        if (n == 0 && m == 0) return 0;
        solve();
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值