Ordering Tasks
From:uva, 10305
Submit
Time Limit: MS Special Judge
John had n tasks to do. Unfortunately, the tasks independent and the execution of one task is only possible if and tasks with already be En executed.
Input
The input would consist of several instances of the problem. Each instance begins with a line containing the integers, 1 <= n <= and M. n is the number of the tasks (numbered from 1 to n) and m are the number of direct Preceden Ce relations between tasks. After this, there'll be m lines with II integers i and J, representing the fact that task i must be executed before task J. An instance with n = m = 0 would finish the input.
Output
for each instance, print a line withNintegers representing the tasks in a possible order of execution.Sample Input
5 4
1 2
2 3
1 3
1 5
0 0
Sample Output
1 4 2) 5 3
Main topic:
With n jobs, M-group relationships, such as a relationship, a, or a, to finish B before you can complete a, you output a set of tasks to complete.
Problem Solving Ideas:
topology ordering.
Code:
#include <iostream> #include <cstdio> #include <queue> #include <string>using namespace std; const int maxn=110,maxm=100000;struct edge{int u,v,next; Edge (int u0=0,int v0=0,int next0=0) {u=u0,v=v0,next=next0;}} E[maxm];int n,m,indegree[maxn],head[maxn],cnt;queue <int> path;void Initial () {cnt=0; for (int i=0;i<=n;i++) {indegree[i]=0; Head[i]=-1; }}void adde (int u,int v) {e[cnt].u=u,e[cnt].v=v,e[cnt].next=head[u],head[u]=cnt++;} void input () {int A, B; for (int i=0;i<m;i++) {scanf ("%d%d", &a,&b); Adde (A, b); indegree[b]++; }}void Tuopu () {queue <int> q; for (int i=1;i<=n;i++) if (indegree[i]==0) Q.push (i); while (!q.empty ()) {int S=q.front (); Path.push (s); Q.pop (); for (int i=head[s];i!=-1;i=e[i].next) {indegree[e[i].v]--; if (indegree[e[i].v]==0) Q.push (E[I].V); }}}void Outresult () {while (!path.empty ()) {printf ("%d", Path.front ()); Path.pop (); if (!path.empty ()) printf (""); } printf ("\ n");} int main () {while (cin>>n>>m&& (n| | m)) {initial (); Input (); Tuopu (); Outresult (); } return 0;}
Ordering Tasks From:uva, 10305 (topological sort)