blob: 24e9371dead70027e26dc164daa282d4b96aec29 (
plain)
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
|
#include <iostream>
#include <vector>
#include <stack>
using std::vector;
using std::stack;
int acyclic(vector<vector<int> > &adj) {
vector<bool> marked(adj.size());
vector<bool> visited(adj.size());
stack<int> st;
for (int i = 0; i < adj.size(); i++) {
if (marked[i])
continue;
st.push(i);
while(!st.empty()) {
int v = st.top();
visited[v] = true;
int s = adj[v].size();
for (int j = 0; j < s; j++) {
int w = adj[v][j];
if (!marked[w]) {
if (visited[w])
return 1;
st.push(w);
}
}
if (st.top() == v) {
visited[v] = false;
marked[v] = true;
st.pop();
}
}
}
return 0;
}
int main() {
size_t n, m;
std::cin >> n >> m;
vector<vector<int> > adj(n, vector<int>());
for (size_t i = 0; i < m; i++) {
int x, y;
std::cin >> x >> y;
adj[x - 1].push_back(y - 1);
}
std::cout << acyclic(adj) << '\n';
}
|