minimario

Cycle Detection

Jun 19th, 2015
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. #include <cstring>
  2. #define push_back pb
  3. #include <vector>
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. int cycle = -1;
  8. vector<int> g[100005];
  9.  
  10. bool visited[100005];
  11.  
  12. void dfs(int v, int parent = -1) {
  13.     visited[v] = 1;
  14.     for (int i=0; i < g[v].size(); i++) {
  15.         if (g[v][i] == parent) {
  16.             continue;
  17.         }
  18.        
  19.         else if (visited[g[v][i]] == 0) {
  20.             dfs(g[v][i], v);
  21.         }
  22.        
  23.         else if (visited[g[v][i]] == 1) {
  24.             cycle = 1;
  25.         }
  26.     }
  27.    
  28.     visited[v] = 2;
  29. }
  30.  
  31. int tot = 0;
  32.  
  33. int main() {
  34.     int x;
  35.     cin >> x;
  36.     int tot = 0;
  37.     for (int i=0; i < x; i++) {
  38.         for (int j=0; j < x; j++) {
  39.             int z;
  40.             cin >> z;
  41.             if (z==1) {
  42.                 tot += 1;
  43.                 g[i].pb(j);
  44.                 g[j].pb(i);
  45.             }
  46.         }
  47.     }
  48.    
  49.     dfs(0);
  50.     int vis = 0;
  51.     for (int i=0; i < 1000; i++) {
  52.         if (visited[i]) { vis += 1; }
  53.     }
  54.    
  55.     for (int i=0; i < x; i++) {
  56.         memset(visited, 0, sizeof(visited));
  57.         dfs(i);
  58.     }
  59.  
  60.     if (cycle == 1) {
  61.         cout << 123 << endl;
  62.     }
  63.    
  64.     if (tot == 2*(x-1) && vis == x) {
  65.         cout << "YES" << endl;
  66.     }
  67.    
  68.     else {
  69.         cout << "NO" << endl;
  70.     }
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment