HDU4324(拓扑排序)

#include <bits/stdc++.h>
using namespace std;
#define maxn 2111
#define maxm 8111111

int t, n;
char mp[maxn][maxn];
struct node {
    int from, to, next;
}edge[maxm];
int head[maxn];
int cnt;
bool vis[maxn];
int indegree[maxn], outdegree[maxn];

void add_edge (int from, int to, int i) {
    node &e = edge[i];
    e.from = from, e.to = to, e.next = head[from], head[from] = i;
}

int topo () {
    int ans = 0;
    queue <int> gg;
    while (!gg.empty ())
        gg.pop ();
    for (int i = 0; i < n; i++) {
        if (!indegree[i])
            gg.push (i), ans++, vis[i] = 1;
    }
    while (!gg.empty ()) {
        int u = gg.front (); gg.pop ();
        for (int i = head[u]; i != -1; i = edge[i].next) {
            int v = edge[i].to;
            if (vis[v])
                continue;
            indegree[v]--;
            if (!indegree[v])
                gg.push (v), ans++, vis[v] = 1;
        }
    }
    return ans;
}

int main () {
    //freopen ("in", "r", stdin);
    scanf ("%d", &t);
    int kase = 0;
    while (t--) {
        scanf ("%d", &n);
        printf ("Case #%d: ", ++kase);
        cnt = 0;
        memset (head, -1, sizeof head);
        memset (indegree, 0, sizeof indegree);
        memset (outdegree, 0, sizeof outdegree);
        memset (vis, 0, sizeof vis);
        for (int i = 0; i < n; i++) {
            scanf ("%s", mp[i]);
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (mp[i][j] == '1') {
                    add_edge (i, j, cnt++);
                    indegree[j]++;
                    outdegree[i]++;
                }
            }
        }
        int cnt = topo ();
        if (cnt != n)
            printf ("Yes\n");
        else
            printf ("No\n");
    }
    return 0;
}

你可能感兴趣的:(HDU4324(拓扑排序))