A project has n tasks. Some pairs say "task a must be done before task b". Decide whether all tasks can be done in some order that obeys every rule. That is possible exactly when the rules have no cycle.
What to build
Store each rule as a directed edge a -> b. Run DFS with three colours: 0 not visited, 1 on the current path, 2 finished. If DFS reaches a vertex with colour 1, there is a cycle.
Requirements
- Use DFS with three colours on a directed graph
- Print
YESwhen an order exists,NOwhen there is a cycle
Input
The first line has n and m. Each of the next m lines has a b: task a before task b.
Output
YES or NO.
Constraints
1 ≤ n ≤ 2,000. 0 ≤ m ≤ 5,000.
Example
Input:
4 3
1 2
2 3
3 4
Output:
YES
Why it works
An edge to a vertex that is still on the current DFS path closes a loop, so a cycle exists. An edge to a finished vertex (colour 2) is harmless, which is why a plain seen array is not enough for directed graphs. With no cycle, the tasks can be listed in reverse order of finishing.
Examples
4 3 1 2 2 3 3 4
YES
3 3 1 2 2 3 3 1
NO
Hints
Hint 1
Make color a vector<int> of n + 1 zeros. In dfs(u): color[u] = 1; for each v: if color[v] == 1 found a cycle; if color[v] == 0 dfs(v); then color[u] = 2.
Hint 2
Add the edge only in one direction: adj[a].push_back(b).
Hint 3
Run dfs from every vertex with colour 0, and keep a global flag for a cycle.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int> > adj;
vector<int> color;
bool cycle = false;
void dfs(int u) {
color[u] = 1;
for (int v : adj[u]) {
if (color[v] == 1) cycle = true;
else if (color[v] == 0) dfs(v);
}
color[u] = 2;
}
int main() {
int n, m;
cin >> n >> m;
adj.assign(n + 1, vector<int>());
color.assign(n + 1, 0);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
}
for (int u = 1; u <= n; u++)
if (color[u] == 0) dfs(u);
cout << (cycle ? "NO" : "YES") << "\n";
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step