LCA.cpp 894 B

12345678910111213141516171819202122232425262728
  1. // use union find
  2. // u : root
  3. // G : graph (children lists)
  4. // q : queries q.first[u] : set of v for asking (u, v), q.second miroir
  5. // f : union-find array, a : ancestor, c : colour (init false)
  6. void makeSet(int *C, int i) { C[i] = i; }
  7. void Tarjan(int u, VI G[], pair<VI*, VI*> q, int f[], int a[], bool c[]) {
  8. makeSet(f,u);
  9. a[u]=u;
  10. for(int v : G[u]) { // for each children of us
  11. Tarjan(v, G, q, f, a, c);
  12. unite(f,u,v);
  13. a[find(f,u)] = u;
  14. }
  15. c[u] = true;
  16. for(VI* qu : {q.first, q.second})
  17. for(int v : qu[u])
  18. if(c[v])
  19. cout<<"LCA("<<u<<','<<v<<")="<<a[find(f,v)]<<endl;
  20. }
  21. void test() {
  22. VI G[6];
  23. G[0].push_back(1); G[0].push_back(2); G[2].push_back(3); G[2].push_back(4); G[3].push_back(5);
  24. VI q1[6], q2[6];
  25. q1[3].push_back(2); q2[2].push_back(3);
  26. int f[6]; int a[6]; bool c[6] = {0, 0, 0, 0, 0, 0};
  27. Tarjan(0, G, make_pair(q1, q2), f, a, c);
  28. }