-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCyclicorAcyclic.app
93 lines (74 loc) · 1.66 KB
/
CyclicorAcyclic.app
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include<iostream>
#include<algorithm>
#include<vector>
#include<sstream>
using namespace std;
#define WH 0
#define GR 1
#define BL 2
#define pb push_back
vector<int> color;
vector<int> path;
int n, m;
bool flag = false;
vector<vector<int> > g;
void dfs(int i)
{
if(flag) return;
color[i] = GR;
path.pb(i);
for(int j = 0; j < g[i].size(); j++){
if(flag) break;
if(color[g[i][j]] == WH){
dfs(g[i][j]);
}
else if(color[g[i][j]] == GR) {
path.pb(g[i][j]);
color[i] = BL;
flag = true;
return;
}
}
color[i] = BL;
if (!flag) path.pop_back();
}
int main()
{
int t;
cin >> t;
while(t-- > 0){
cin >> n >> m;
g.clear();
g.resize(n + 1);
color.clear();
color.resize(n + 1);
flag = false;
for(int i = 0; i < m; i++){
int x, y;
cin >> x >> y;
g[x].pb(y);
}
path.clear();
for(int i = 1; i <= n; i++){
if(color[i] == WH){
dfs(i);
if(flag){
cout << "NO" << endl;
int start = path.back();
int j = 0;
while(path[j] != start){
j++;
}
cout << path.size() - j-1 << endl;
while(j < path.size()){
cout << path[j++] << " ";
}
cout << endl;
break;
}
}
}
if(!flag) cout << "YES" << endl;
}
return 0;
}