Advertisement
tomalikem

KOM

Apr 26th, 2018
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 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.     visited[x] = gray;
  19.     Node* neighbor = graph[x];
  20.     while(neighbor != NULL) {
  21.         if(visited[neighbor->n] == gray) return true;
  22.         if(visited[neighbor->n] == white && find_cycle_from(graph, visited, n, neighbor->n)) return true;
  23.         neighbor = neighbor->next;
  24.     }
  25.  
  26.     visited[x] = black;
  27.     return false;
  28. }
  29.  
  30. bool has_cycle(Node** graph, int n) {
  31.     color visited[n];
  32.     for (int i=0; i<n; i++) visited[i] = white;
  33.     for(int i = 0; i<n; i++) {
  34.         if (visited[i] == white) {
  35.             if (find_cycle_from(graph, visited, n, i)) return true;
  36.         }
  37.     }
  38.     return false;
  39. }
  40.  
  41. int main() {
  42.     int n, k;
  43.     cin >> n;
  44.     Node **graph = new Node*[n];
  45.     for(int i=0;i<n;i++) graph[i] = NULL;
  46.     cin >> k;
  47.     for(int i=0; i<k; i++) {
  48.         Node* tmp = new Node;
  49.         int x, y;
  50.         cin >> x;
  51.         cin >> y;
  52.         if(x > n) {
  53.             return 44;
  54.         }
  55.         if(y > n) {
  56.             return 45;
  57.         }
  58.         tmp->n = y;
  59.         tmp->next = graph[x];
  60.         graph[x] = tmp;
  61.     }
  62.     cout << (has_cycle(graph, n) ? "CYKL" : "OK") << endl;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement