-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path10305.cpp
79 lines (73 loc) · 1.13 KB
/
10305.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
10305 - Ordering Tasks
*/
#include<bits/stdc++.h>
using namespace std;
#define NODE 101
int graph[NODE][NODE];
int n,m;
void dfs(int u,bool visited[],stack<int>&stk)
{
visited[u]=true;
for(int v=1; v<=n; v++)
{
if(graph[u][v])
{
if(!visited[v])
{
dfs(v,visited,stk);
}
}
}
stk.push(u);
}
void top_sort()
{
stack<int>stk;
bool visited[n];
for(int i=1; i<=n; i++)
visited[i]=false;
for(int i=1; i<=n; i++)
{
if(!visited[i])
{
dfs(i,visited,stk);
}
}
printf("%d",stk.top());
stk.pop();
while(!stk.empty())
{
printf(" %d",stk.top());
stk.pop();
}
printf("\n");
}
int main()
{
while(scanf("%d %d",&n,&m)==2)
{
if(n==0 && m==0)
break;
memset(graph,0,sizeof(graph));
for(int i=1; i<=m; i++)
{
int a,b;
scanf("%d %d",&a,&b);
graph[a][b]=1;
}
top_sort();
}
return 0;
}
/*
Sample Input
5 4
1 2
2 3
1 3
1 5
0 0
Sample Output
1 4 2 5 3
*/