Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- CF 915D
- Print cycle in directed graph
- */
- #include <bits/stdc++.h>
- using namespace std;
- #define MAX 505
- int n, m;
- vector<int> adj[MAX];
- int cycle = -1;
- int vis[MAX], par[MAX];
- vector<int> V;
- int x, y;
- void dfs2(int u)
- {
- vis[u] = 1;
- //cout << "u " << u << " " << vis[u] << endl;
- for(int i=0; i<adj[u].size(); i++){
- int v = adj[u][i];
- if(u == x && v == y) continue;
- //cout << "v " << v << " " << vis[v] << endl;
- if(vis[v] == 1){
- cycle = v;
- return;
- }
- if(vis[v] == 0){
- dfs2(v);
- }
- }
- vis[u] = 2;
- }
- void dfs(int u, int parent)
- {
- vis[u] = 1;
- par[u] = parent;
- for(int i=0; i<adj[u].size(); i++){
- int v = adj[u][i];
- if((vis[v] == 1) && (cycle == -1)){
- cycle = v;
- V.push_back(cycle);
- int node = u;
- for(; node!= cycle; node=par[node]) V.push_back(node);
- V.push_back(cycle);
- reverse(V.begin(), V.end());
- return;
- }
- if(vis[v] == 0){
- dfs(v, u);
- }
- }
- vis[u] = 2;
- }
- int main()
- {
- //freopen("in.txt", "r", stdin);
- scanf("%d %d", &n, &m);
- for(int i=0; i<m; i++){
- int u, v;
- scanf("%d %d", &u, &v);
- adj[u].push_back(v);
- }
- memset(vis, 0, sizeof vis);
- for(int i=1; i<=n; i++){
- if(vis[i] == 0){
- dfs(i, -1);
- if(cycle != -1) break;
- }
- }
- if(cycle == -1){
- cout << "YES";
- return 0;
- }
- memset(vis, 0, sizeof vis);
- for(int i=0; i<V.size()-1; i++){
- x = V[i], y = V[i+1], cycle = -1;
- memset(vis, 0, sizeof vis);
- for(int j=1; j<=n; j++){
- if(vis[j] == 0) dfs2(j);
- }
- if(cycle == -1){
- cout << "YES";
- return 0;
- }
- }
- cout << "NO";
- }
Advertisement
Add Comment
Please, Sign In to add comment