LCA.cpp 812 B

123456789101112131415161718192021222324252627
  1. // use union find
  2. // u : root
  3. // G : graph (children lists)
  4. // q : queries q[u] : set of v for asking (u, v) (must be symmetric)
  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[], 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(int v : q[u])
  17. if(c[v])
  18. cout<<"LCA("<<u<<','<<v<<")="<<a[find(f,v)]<<endl;
  19. }
  20. void test() {
  21. VI G[6];
  22. 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);
  23. VI q[6];
  24. q[3].push_back(2); q[2].push_back(3);
  25. int f[6]; int a[6]; bool c[6] = {0, 0, 0, 0, 0, 0};
  26. Tarjan(0, G, q, f, a, c);
  27. }