UVa 10305 Ordering Tasks

来源:互联网 发布:php关闭微信浏览器 编辑:程序博客网 时间:2024/06/02 00:58

Description

拓扑排序

Algorithm

拓扑排序算法
参考拓扑排序

Code

#include <cstdio>#include <cstring>#include <iostream>using namespace std;int n, m, t;const int maxn = 100 + 9;bool g[maxn][maxn];int c[maxn], topo[maxn];void dfs(int u){  c[u] = -1;  for (int v = 1; v <= n; v++)    if (g[u][v] && !c[v]) dfs(v);  c[u] = 1;  topo[--t] = u;}void solve(){  memset(g, 0, sizeof(g));  memset(c, 0, sizeof(c));  memset(topo, 0, sizeof(topo));  for (int i = 0; i < m; i++)  {    int x, y;    cin >> x >> y;    g[x][y] = true;  }  t = n;  for (int u = 1; u <= n; u++)    if (!c[u]) dfs(u);  cout << topo[0];  for (int i = 1; i < n; i++)    cout << ' ' << topo[i];  cout << endl;}int main(){//  freopen("input.txt", "r", stdin);  for (;;)  {    cin >> n >> m;    if (n == 0 && m == 0) break;    solve();  }}
0 0
原创粉丝点击