Advertisement
Guest User

Untitled

a guest
Apr 26th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. typedef struct Node {
  6.     int n;
  7.     struct Node* next;
  8. } Node;
  9.  
  10. enum color {
  11.     white,
  12.     gray,
  13.     black
  14. };
  15.  
  16. bool find_cycle_from(Node** graph, color* visited, int n, int x) {
  17.     // gray color means "we already processed this node in current lookup" - once x is gray, we are sure we've got a cycle
  18.     if(visited[x] == gray) return true;
  19.     // mark x grey
  20.     visited[x] = gray;
  21.  
  22.     // iterate over each neighbour and proceed with DFS (recursively or using stack)
  23.     Node *tmp = graph[x];
  24.     bool flag = false;
  25.     while(tmp != NULL) {
  26.         if(visited[tmp->n] != black) {
  27.             if(find_cycle_from(graph, visited, n, tmp->n)) return true;
  28.         }
  29.         tmp = tmp->next;
  30.     }
  31.         // once you found cycle - return immediately
  32.    
  33.     // black means "ok, we finally processed that node" - mark x black
  34.     visited[x] = black;
  35.     // found nothing? Return
  36.     return false;
  37. }
  38.  
  39. bool has_cycle(Node** graph, int n) {
  40.     color visited[n];
  41.     for (int i=0; i<n; i++) visited[i] = white;
  42.     for(int i = 0; i<n; i++) {
  43.         if (visited[i] == white) {
  44.             if (find_cycle_from(graph, visited, n, i)) return true;
  45.         }
  46.     }
  47.     return false;
  48. }
  49.  
  50. int main() {
  51.     int n, k;
  52.     cin >> n;
  53.     Node **graph = new Node*[n];
  54.     cin >> k;
  55.     for(int i=0; i<k; i++) {
  56.         Node* tmp = new Node;
  57.         int x, y;
  58.         cin >> x;
  59.         cin >> y;
  60.         tmp->n = y;
  61.         tmp->next = graph[x];
  62.         graph[x] = tmp;
  63.     }
  64.     cout << (has_cycle(graph, n) ? "CYKL" : "OK") << endl;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement