Uva 10305 Ordering Tasks(拓扑排序)

来源:互联网 发布:kali linux洪水攻击 编辑:程序博客网 时间:2024/05/22 15:04
/*Kahn 算法 复杂度:O(E+V)L← Empty list that will contain the sorted elementsS ← Set of all nodes with no incoming edgeswhile S is non-empty do    remove a node n from S    insert n into L    for each node m with an edge e from n to m do        remove edge e from the graph        if m has no other incoming edges then            insert m into S      if graph has edges then    return error (graph has at least onecycle)else     return L (a topologically sortedorder)*/#include <iostream>#include <cstdio>#include <cstring>#include <queue>using namespace std;int n,m;int graph[105][105];int indegree[105];int ret[105];queue <int> q;void toposort(){for(int i=1;i<=n;i++){if(!indegree[i])q.push(i);}int cnt=0;while(!q.empty()){int tmp=q.front();q.pop();ret[++cnt]=tmp;for(int i=1;i<=n;i++){if(graph[tmp][i]==1){graph[tmp][i]--;q.push(i);}}}for(int i=1;i<=n;i++){if(i!=n){printf("%d ",ret[i]);}else{printf("%d\n",ret[i]);}}}int main(){while(scanf("%d %d",&n,&m)!=EOF&&(m||n)){memset(graph,0,sizeof(graph));memset(indegree,0,sizeof(indegree));memset(ret,0,sizeof(ret));for(int i=1;i<=m;i++){int a,b;scanf("%d %d",&a,&b);if(!graph[a][b]){graph[a][b]=1;indegree[b]++;}}toposort();}return 0;}



/*基于DFS的拓扑排序L ← Empty list that will contain the sorted nodesS ← Set of all nodes with no outgoing edgesfor each node n in S do    visit(n) function visit(node n)    if n has not been visited yet then        mark n as visited        for each node m with an edgefrom m to ndo            visit(m)        add n to L*/#include <cstdio>#include <cstring>#include <queue>using namespace std;const int maxn = 101;int n, m, t;int gragh[maxn][maxn], res[maxn], c[maxn];bool dfs(int u) {c[u] = -1;for (int v = 0; v < n; v++)if (gragh[u][v])if (c[v] < 0)return false;else if (!c[v] && !dfs(v))return false;c[u] = 1;res[--t] = u;return true;}bool toposort() {t = n;memset(c, 0, sizeof(c));for (int u = 0; u < n; u++)if (!c[u])if (!dfs(u))return false;return true;}int main() {while (scanf("%d%d", &n, &m) && (n || m)) {memset(gragh, 0, sizeof(gragh));int a, b;for (int i = 0; i < m; i++) {scanf("%d%d", &a, &b);gragh[a-1][b-1] = 1;}toposort();for (int i = 0; i < n; i++)printf("%d ", res[i] + 1);printf("\n");}return 0;}


0 0