Advertisement
tomalikem

HYP

Apr 26th, 2018
66
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.     components[i] = component_no;
  12.     Node* neighbor = graph[i];
  13.     while(neighbor != NULL) {
  14.         if(components[neighbor->n] == -1) {
  15.             dfs(graph, components, n, neighbor->n, component_no);
  16.         }
  17.         neighbor = neighbor->next;
  18.     }
  19. }
  20.  
  21. int* count_components(Node** graph, int n) {
  22.     // this array shows to which component each node belongs
  23.     // -1 means that node hasn't been visited yet
  24.     int* components = new int[n];
  25.     for(int i=0; i<n; i++) components[i] = -1;
  26.     // prepare components counter
  27.     int counter = 0;
  28.     for(int i=0; i<n; i++) {
  29.         if(components[i] == -1) {
  30.             dfs(graph, components, n, i, counter++);
  31.         }
  32.     }
  33.  
  34.     return components;
  35. }
  36.  
  37. int main() {
  38.     ios::sync_with_stdio(false);
  39.     int n, k, p;
  40.     cin >> n;
  41.     Node **graph = new Node*[n];
  42.     for(int i=0;i<n;i++) graph[i] = NULL;
  43.     cin >> k;
  44.     cin >> p;
  45.     for (int i=0; i<k; i++) {
  46.         Node *tmp1 = new Node, *tmp2 = new Node;
  47.         int x, y;
  48.         cin >> x;
  49.         cin >> y;
  50.         tmp1->n = y;
  51.         tmp1->next = graph[x];
  52.         graph[x] = tmp1;
  53.         tmp2->n = x;
  54.         tmp2->next = graph[y];
  55.         graph[y] = tmp2;
  56.     }
  57.     int* components = count_components(graph, n);
  58.     for (int i=0; i<p; i++) {
  59.         int x, y;
  60.         cin >> x;
  61.         cin >> y;
  62.         cout << (components[x] == components[y] ? "TAK" : "NIE") << endl;
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement