【紫书】Ordering Tasks UVA

题意:给你一些任务1~n,给你m个数对(u,v)代表做完u才能做v 让你给出一个做完这些任务的合理顺序。

题解:拓扑排序版题 dfs到底再压入栈。

#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include<stdio.h>
#include<algorithm>
#include<string>
#include<vector>
#include<list>
#include<set>
#include<iostream>
#include<string.h>
#include<queue>
#include<string>
#include<sstream>
using namespace std;
const int maxn = 100 + 5;
int G[maxn][maxn];
int c[maxn];
list<int>topo;
int n, m;
bool dfs(int u) {
    c[u] = -1;
    for (int v = 1; v <= n; v++)if(G[u][v]) {
        if (c[v] == -1)return false;//正在dfs栈中
        else if (!c[v] && !dfs(v))return false;//若未dfs,就dfs一遍.
    }
    c[u] = 1; topo.push_front(u);
    return true;
}
bool toposort() {
    memset(c, 0, sizeof(c));
    for (int u = 1; u <= n; u++)if(c[u]==0) {
        if (!dfs(u))return false;
    }
    return true;
}
int main() {
    
    while (cin >> n >> m)
    {
        if (n == m&&n == 0)break;
        memset(G, 0, sizeof(G));
        topo.clear();
        for (int i = 0; i < m; i++) {
            int a, b;
            cin >> a >> b;
            G[a][b] = 1;
        }
        if (toposort()) {
            cout << topo.front();
            topo.pop_front();
            for (auto t : topo) cout << ' '<< t ;
            cout << endl;
        }
    }
        

    system("pause");
    return 0;
}

附:不判环的ac代码(便于理解)

#include "stdio.h"
#include<stdio.h>
#include<algorithm>
#include<string>
#include<vector>
#include<list>
#include<set>
#include<iostream>
#include<string.h>
#include<queue>
#include<string>
#include<sstream>
#include<stack>
using namespace std;
const int maxn = 100 + 5;
vector<int> G[maxn];
int c[maxn];
stack<int>topo;
int n, m;
void dfs(int u) {
    c[u] = 1;
    for (int j = 0; j <G[u].size(); j++)
    {
        int v = G[u][j];
        if (!c[v])dfs(v);    
    }
    c[u] = 1; topo.push(u);
    
}
void toposort() {
    memset(c, 0, sizeof(c));
    for (int u = 1; u <= n; u++)if(c[u]==0) {dfs(u);}    
}
int main() {
    
    while (cin >> n >> m)
    {
        if (n == m&&n == 0)break;
        for (int i = 1; i <= n; i++)G[i].clear();
        while (!topo.empty()) topo.pop();
        for (int i = 0; i < m; i++) {
            int a, b;
            cin >> a >> b;
            G[a].push_back(b);
        }
        toposort();
        cout << topo.top(); topo.pop();
        while (!topo.empty()) {
            cout << ' ' << topo.top(); topo.pop();
        }
        cout << endl;
    }
        

    system("pause");
    return 0;
}
成功的路并不拥挤,因为大部分人都在颓(笑)
原文地址:https://www.cnblogs.com/SuuT/p/8822245.html