Advertisement
erek1e

IOI '14 P3 - Game

Jul 14th, 2023
1,053
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. // DSU
  7. int components;
  8. vector<int> parent;
  9. vector<vector<int>> questions; // between pairs of components
  10. int root(int i) {
  11.     return parent[i] < 0 ? i : (parent[i] = root(parent[i]));
  12. }
  13. void unite(int i, int j) {
  14.     i = root(i), j = root(j);
  15.     if (i == j) return;
  16.     if (parent[i] > parent[j]) swap(i, j);
  17.     parent[i] += parent[j];
  18.     parent[j] = i;
  19.  
  20.     // only n unions, O(n) each, so O(n^2) in total
  21.     int N = parent.size();
  22.     for (int k = 0; k < N; ++k) {
  23.         if (parent[k] < 0) {
  24.             // these two are equal values
  25.             questions[k][i] += questions[k][j];
  26.             questions[i][k] += questions[j][k];
  27.         }
  28.     }
  29. }
  30.  
  31. void initialize(int n) {
  32.     parent.assign(n, -1);
  33.     questions.assign(n, vector<int>(n));
  34.     components = n;
  35. }
  36. int hasEdge(int u, int v) {
  37.     if (components == 2) return 0;
  38.     u = root(u), v = root(v);
  39.     ++questions[u][v], ++questions[v][u];
  40.     if (questions[u][v] == parent[u] * parent[v]) {
  41.         unite(u, v);
  42.         return 1;
  43.     } else return 0;
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement