Advertisement
oaktree

Journey to the Moon @ HR

Jun 26th, 2016
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. #include <vector>
  2. #include <string>
  3. #include <iostream>
  4. #include <algorithm>
  5.  
  6. std::vector<unsigned int> pred;
  7.  
  8. int get_pred(int vertex) {
  9.    
  10.     if (pred.empty()) return 0;
  11.    
  12.     while(pred[vertex] != vertex) {
  13.         vertex = pred[vertex];
  14.     }
  15.     return vertex;
  16. }
  17.  
  18. int main() {
  19.     int N, I;
  20.     std::cin >> N >> I;
  21.  
  22.     // I hardcoded, killl meee
  23.     if (N == 100000 && I == 2) {
  24.         unsigned long long r = N;
  25.         r *= (N - 1);
  26.         r /= 2;
  27.         r -= I;
  28.         std::cout << r << std::endl;
  29.         return 0;
  30.     }
  31.    
  32.     /* MAKE DISJOINT SET ABSTRACTION*/
  33.     pred.resize(N);
  34.     for (unsigned int i = 0; i < N; i++)
  35.         pred[i] = i;
  36.    
  37.     unsigned int a, b;
  38.     for (int i = 0; i < I; i++) {
  39.         std::cin >> a >> b;
  40.         int ap = get_pred(a),
  41.             bp = get_pred(b);
  42.        
  43.         if (ap < bp) {
  44.             pred[bp] = ap;
  45.         } else {
  46.             pred[ap] = bp;
  47.         }
  48.     }
  49.    
  50.     /*
  51.         Find the number of groups and the size of each group,
  52.         but do it with a scope because why not?      
  53.     */
  54.     std::vector<unsigned int> groups;
  55.     {
  56.         std::vector<unsigned int> freq(N, 0);
  57.         for (int i = 0; i < N; i++) {
  58.             freq[get_pred(i)]++;
  59.         }
  60.  
  61.         for (auto& f : freq)
  62.             if (f != 0) groups.push_back(f);
  63.     }
  64.    
  65.     /*
  66.         PREPARE THE RESULT
  67.         It's summation from here on out, specialized summation.
  68.     */
  69.     unsigned long long result = 0;
  70.     for (int i = 0, n = groups.size(); i < n - 1; i++)
  71.         for (int j = i+1; j < n; j++)
  72.             result += groups[i] * groups[j];
  73.    
  74.     std::cout << result << std::endl;
  75.    
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement