UVa 10305 - Ordering Tasks

传送门UVa 10305 - Ordering Tasks


拓扑排序的入门题。

刚开始理解起来有一点困难,现在还是半知半解,当初学树的时候也这样。过几天再来看看。


#include <cstdio>
#include <cstring>
using namespace std;

const int MAXN = 105;
int graph[MAXN][MAXN];
int n, t;
int topo[MAXN];
int c[MAXN];

bool DFS(int u);
bool toposort();

int main()
{
    //freopen("input.txt", "r", stdin);
    int m, i;
    while (scanf("%d%d", &n, &m))
    {
        int u, v;
        if (n + m == 0)
            break;
        memset(graph, 0, sizeof(graph));
        for (i = 0; i < m; i++)
        {
            scanf("%d%d", &u, &v);
            graph[u][v] = 1;
        }
        if (toposort())
        {
            for (i = 0; i < n - 1; i++)
                printf("%d ", topo[i]);
            printf("%d\n", topo[i]);
        }
    }
    return 0;
}

bool toposort()
{
    int i;
    t = n;
    memset(c, 0, sizeof(c));
    for (i = 1; i <= n; i++)
        if (!c[i] && !DFS(i))
            return false;
    return true;
}

bool DFS(int u)
{
    c[u] = -1;
    for (int v = 1; v <= n; v++)
    {
        if (graph[u][v])
        {
            if (c[v] < 0)
                return false;
            else if (!c[v] && !DFS(v))
                return false;
        }
    }
    c[u] = 1;
    topo[--t] = u;
    return true;
}


你可能感兴趣的:(ACM,uva)