Advertisement
Guest User

Untitled

a guest
Apr 26th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 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. void dfs(Node** graph, int* components, int n, int i, int component_no) {
  11.     if(components[i] == -1) components[i] = component_no;
  12.     Node *tmp = graph[i];
  13.     while(tmp != NULL) {
  14.         if(components[tmp->n] == -1) dfs(graph, components, n, tmp->n, component_no);
  15.         tmp = tmp->next;
  16.     }
  17.     // traverse the graph and mark all nodes which belong to the component
  18. }
  19.  
  20. int* count_components(Node** graph, int n) {
  21.     // this array shows to which component each node belongs
  22.     // -1 means that node hasn't been visited yet
  23.     int* components = new int[n];
  24.     int component_no = 0;
  25.     for(int i=0; i<n; i++) components[i] = -1;
  26.     // prepare components counter
  27.     for(int i=0; i<n; i++) {
  28.         if(components[i] == -1) dfs(graph, components, n, i, component_no++);
  29.     }
  30.     // in loop: find unvisited node, call DFS/BFS
  31.  
  32.     return components;
  33. }
  34.  
  35. int main() {
  36.     int n, k, p;
  37.     cin >> n;
  38.     Node **graph = new Node*[n];
  39.     cin >> k;
  40.     cin >> p;
  41.     for (int i=0; i<k; i++) {
  42.         Node *tmp1 = new Node, *tmp2 = new Node;
  43.         int x, y;
  44.         cin >> x;
  45.         cin >> y;
  46.         tmp1->n = y;
  47.         tmp1->next = graph[x];
  48.         graph[x] = tmp1;
  49.         tmp2->n = x;
  50.         tmp2->next = graph[y];
  51.         graph[y] = tmp2;
  52.     }
  53.     int* components = count_components(graph, n);
  54.     for (int i=0; i<p; i++) {
  55.         int x, y;
  56.         cin >> x;
  57.         cin >> y;
  58.         cout << (components[x] == components[y] ? "TAK" : "NIE") << endl;
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement