UVA - 1572 Self-Assembly(拓扑排序判断成环)

点击打开题目链接
有n种边上带标号的正方形,每种无穷多个,特定标号可以相连,判断是否能够组成无限大空间结构。
标号做点,正方形作边,构建有向图,拓扑排序判断是否成环即可。
代码:

#include<bits/stdc++.h>

using namespace std;
const int maxn = 52;
int n;
string s;
int vis[maxn];
int g[maxn][maxn];

int id(char a, char b) {
    return (a - 'A') * 2 + (b == '+' ? 0 : 1);
}

void connect(char a1, char a2, char b1, char b2) {
    if(a1 == '0' || b1 == '0') return;
    int u = id(a1, a2) ^ 1, v = id(b1, b2);
    g[u][v] = 1;
}

int toposort(int u) {
    vis[u] = -1;
    for(int v = 0; v < maxn; v++) {
        if(g[u][v]) {
            if(vis[v] == -1) return 1;
            else if(!vis[v] && toposort(v)) return 1;
        }
    }
    vis[u] = 1;
    return 0;
}

int cycle() {
    memset(vis, 0, sizeof(vis));
    for(int i = 0; i < maxn; i++) {
        if(!vis[i]) {
            if(toposort(i)) return 1;
        }
    }
    return 0;
}

int main() {
    //ios::sync_with_stdio(false);
    while(cin >> n) {
        memset(g, 0, sizeof(g));
        while(n--) {
            cin >> s;
            for(int i = 0; i < 4; i++) {
                for(int j = 0; j < 4; j++) {
                    if(i != j) connect(s[2 * i], s[2 * i + 1], s[2 * j], s[2 * j + 1]);
                }
            }
        }
        printf("%s\n",cycle() ? "unbounded" : "bounded");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/l1832876815/article/details/79306091