【紫书】Ordering Tasks UVA - 10305 拓扑排序:dfs到底再输出。

题意:给你一些任务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 = + ;
int G[maxn][maxn];
int c[maxn];
list<int>topo;
int n, m;
bool dfs(int u) {
c[u] = -;
for (int v = ; v <= n; v++)if(G[u][v]) {
if (c[v] == -)return false;//正在dfs栈中
else if (!c[v] && !dfs(v))return false;//若未dfs,就dfs一遍.
}
c[u] = ; topo.push_front(u);
return true;
}
bool toposort() {
memset(c, , sizeof(c));
for (int u = ; u <= n; u++)if(c[u]==) {
if (!dfs(u))return false;
}
return true;
}
int main() { while (cin >> n >> m)
{
if (n == m&&n == )break;
memset(G, , sizeof(G));
topo.clear();
for (int i = ; i < m; i++) {
int a, b;
cin >> a >> b;
G[a][b] = ;
}
if (toposort()) {
cout << topo.front();
topo.pop_front();
for (auto t : topo) cout << ' '<< t ;
cout << endl;
}
} system("pause");
return ;
}

附:不判环的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 = + ;
vector<int> G[maxn];
int c[maxn];
stack<int>topo;
int n, m;
void dfs(int u) {
c[u] = ;
for (int j = ; j <G[u].size(); j++)
{
int v = G[u][j];
if (!c[v])dfs(v);
}
c[u] = ; topo.push(u); }
void toposort() {
memset(c, , sizeof(c));
for (int u = ; u <= n; u++)if(c[u]==) {dfs(u);}
}
int main() { while (cin >> n >> m)
{
if (n == m&&n == )break;
for (int i = ; i <= n; i++)G[i].clear();
while (!topo.empty()) topo.pop();
for (int i = ; 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 ;
}
上一篇:linux yum命令详解


下一篇:Js中获取frames中的元素