UVa 10305 - Ordering Tasks

19 篇文章 0 订阅

传送门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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值