Advertisement
Guest User

SRM 692 Div 1 900

a guest
Jun 10th, 2016
331
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. typedef pair<ll, ll> pii;
  5.  
  6. const ll m1 = 1e9;
  7. const ll m2 = 1e6;
  8. const int MAXN = 3e5+5;
  9.  
  10. #define A first
  11. #define B second
  12.  
  13. ll n, ans[MAXN], sub[MAXN], totsub[MAXN];
  14. vector<pii> g[MAXN];
  15.  
  16. // vertex v, tot = total so far, place = whether we have some vertex already walking along here
  17. void dfs(int v, ll tot, ll place = -1, ll disttotop = 0) {
  18.     //cout << v << ' ' << tot << ' ' << place << ' ' << disttotop << endl;
  19.     ll ind = -1, tot1 = tot, dist1 = disttotop;
  20.     for (pii u : g[v])
  21.         if (2*sub[u.A] > sub[v])
  22.             ind = u.A;
  23.     if (place == -1)
  24.         place = v;
  25.     while (true) {
  26.         bool y = false;
  27.         for (pii u : g[place])
  28.             if (2*sub[u.A] > sub[v]) {
  29.                 place = u.A; y = true;
  30.                 tot1 += u.B*(sub[v]-2*sub[u.A]);
  31.                 disttotop += u.B;
  32.                 break;
  33.             }
  34.         if (!y)
  35.             break;
  36.     }
  37.  
  38.     ans[v] = tot1;
  39.  
  40.     for (pii u : g[v]) {
  41.         if (u.A != ind)
  42.             dfs(u.A, totsub[u.A]);
  43.         else {
  44.             ll distofv = totsub[v]-(totsub[u.A]+u.B*sub[u.A]);
  45.             tot1 -= distofv+disttotop*(sub[v]-sub[u.A]);
  46.             dfs(u.A, tot1, place, disttotop-u.B);
  47.         }
  48.     }
  49. }
  50.  
  51. void dfs1(ll v) {
  52.     sub[v] = 1;
  53.     for (pii u : g[v]) {
  54.         dfs1(u.A);
  55.         sub[v] += sub[u.A];
  56.         totsub[v] += u.B*sub[u.A]+totsub[u.A];
  57.     }
  58. }
  59.  
  60. class TreeSums {
  61. public:
  62.     ll findSums(int N, int seed, int C, int D) {
  63.         n = N;
  64.         ll cur = seed;
  65.         for (int i = 0; i <= N-2; ++i) {
  66.             cur = (C*cur+D)%m1;
  67.             ll pi = cur%(i+1);
  68.             g[pi].push_back(pii(i+1, (C*cur+D)%m2));
  69.             cur = (C*cur+D)%m1;
  70.         }
  71.  
  72.         dfs1(0);
  73.         dfs(0, totsub[0]);
  74.         ll fin = 0;
  75.         for (int i = 0; i < n; ++i) {
  76.             fin ^= ans[i]; //cout << i << ' ' << ans[i] << endl;
  77.         }
  78.         return fin;
  79.     }
  80. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement