File tree 1 file changed +69
-0
lines changed 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+ #define int long long
4
+ const int N=1e5 +10 ;
5
+ const int INF=1e18 ;
6
+ int n,m;
7
+ vector<int >adj[N];
8
+ bool detectCycle (vector<int >&vis,int v){
9
+ if (vis[v]==2 )return true ;
10
+ vis[v]=2 ;
11
+ for (auto it:adj[v]){
12
+ if (vis[it]!=1 ){
13
+ if (detectCycle (vis,it)){
14
+ return true ;
15
+ }
16
+ }
17
+ }
18
+ vis[v]=1 ;
19
+ return false ;
20
+ }
21
+ bool cycleDect (int n){
22
+ vector<int > vis (n+1 ,0 );
23
+ for (int i=0 ;i<n;i++){
24
+ if (!vis[i]){
25
+ if (detectCycle (vis, i)){
26
+ return true ;
27
+ }
28
+ }
29
+ }
30
+ return false ;
31
+ }
32
+ void topoDfs (int v,vector<int >& visited,vector<int >& res){
33
+ visited[v]=1 ;
34
+ for (auto it:adj[v]){
35
+ if (!visited[it]){
36
+ topoDfs (it,visited, res);
37
+ }
38
+ }
39
+ res.push_back (v);
40
+ }
41
+ signed main () {
42
+ cin>>n>>m;
43
+ vector<pair<int ,int >>g[n+1 ];
44
+ for (int i=0 ;i<m;i++){
45
+ int x,y,wt;
46
+ cin>>x>>y;
47
+ adj[x].push_back (y);
48
+ }
49
+ bool isCy=cycleDect (n);
50
+ if (isCy){
51
+ cout<<" IMPOSSIBLE" <<endl;
52
+ }
53
+ else {
54
+ vector<int > visited (n+5 ,0 );
55
+ vector<int >res;
56
+ for (int i=1 ;i<=n;i++){
57
+ if (!visited[i]){
58
+ topoDfs (i,visited,res);
59
+ }
60
+ }
61
+ reverse (res.begin (),res.end ());
62
+ for (auto y:res){
63
+ cout<<y<<" " ;
64
+ }
65
+ cout<<endl;
66
+ }
67
+ return 0 ;
68
+ }
69
+
You can’t perform that action at this time.
0 commit comments