Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- typedef struct Node {
- int n;
- struct Node* next;
- } Node;
- enum color {
- white,
- gray,
- black
- };
- bool find_cycle_from(Node** graph, color* visited, int n, int x) {
- // gray color means "we already processed this node in current lookup" - once x is gray, we are sure we've got a cycle
- visited[x] = gray;
- Node* neighbor = graph[x];
- while(neighbor != NULL) {
- if(visited[neighbor->n] == gray) return true;
- if(visited[neighbor->n] == white && find_cycle_from(graph, visited, n, neighbor->n)) return true;
- neighbor = neighbor->next;
- }
- visited[x] = black;
- return false;
- }
- bool has_cycle(Node** graph, int n) {
- color visited[n];
- for (int i=0; i<n; i++) visited[i] = white;
- for(int i = 0; i<n; i++) {
- if (visited[i] == white) {
- if (find_cycle_from(graph, visited, n, i)) return true;
- }
- }
- return false;
- }
- int main() {
- int n, k;
- cin >> n;
- Node **graph = new Node*[n];
- for(int i=0;i<n;i++) graph[i] = NULL;
- cin >> k;
- for(int i=0; i<k; i++) {
- Node* tmp = new Node;
- int x, y;
- cin >> x;
- cin >> y;
- if(x > n) {
- return 44;
- }
- if(y > n) {
- return 45;
- }
- tmp->n = y;
- tmp->next = graph[x];
- graph[x] = tmp;
- }
- cout << (has_cycle(graph, n) ? "CYKL" : "OK") << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement