John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task is only possible if other tasks have already been executed.
Input
The input will consist of several instances of the problem. Each instance begins with a line containing two integers, 1<=n<=100 and
m.n is the number of tasks (numbered from 1 to n) and m is the number of direct precedence relations between tasks. After this, there will be
m lines with two integers i and j , representing the fact that task i must be executed before task j . An instance with n = m= 0 will nish the input.
Output
For each instance, print a line with n integers representing the tasks in a possible order of execution.
Sample Input
Sample Input
5 4
1 2
2 3
1 3
1 5
0 0
Sample Output
1 4 2 5 3
MY accepted code Code:
#include<bits/stdc++.h>
using namespace std;
long long visited[100];
vector <int> grp[200];
map<int,int>vis;
stack<int>st;
int n;
int topologicalSortUtill(int v)
{
vis[v] = 1;
int l=grp[v].size();
int u;
for(int i=0; i<l; i++)
{
u=grp[v][i];
if (!vis[u])
topologicalSortUtill(u);
}
st.push(v);
}
int topologicalSort()
{
for(int i=1; i<=n; i++)
vis[i]=0;
for(int i=1; i<=n; i++)
if(vis[i]==0)
topologicalSortUtill(i);
int c=0;
while(st.empty()==0)
{
c++;
cout<<st.top();
if(c<n)
cout<<" ";
st.pop();
}
cout<<endl;
}
int main()
{
int m,i,j,a,b;
while(cin>>n>>m)
{
if(n==0&&m==0)
break;
for(i=1; i<=m; i++)
{
cin>>a>>b;
grp[a].push_back(b);
}
//for(i=0;i<n;i++)
topologicalSort();
}
return 0;
}
/*
6 6
5 2
5 0
4 0
4 1
2 3
3 1
*/
No comments:
Post a Comment