Advertisement
Gustavo_Inzunza

Lowest common ancestor

Jun 12th, 2013
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.63 KB | None | 0 0
  1. bool adj[9][9];
  2. bool visit[9];  
  3. int lca[9][9];  
  4.  
  5. int find(int x)
  6. {
  7.     return x == p[x] ? x : (p[x] = find(p[x]));
  8. }
  9.  
  10. int DFS(int x)
  11. {
  12.     if (visit[x]) return;
  13.     visit[x] = true;
  14.  
  15.     for (int y=0; y<9; ++y)
  16.         if (visit[y])
  17.             lca[x][y] = lca[y][x] = find(y);
  18.  
  19.     // DFS
  20.     for (int y=0; y<9; ++y)
  21.         if (adj[x][y])
  22.         {
  23.             DFS(y);
  24.             p[y] = x;  
  25.         }
  26. }
  27. void demo()
  28. {
  29.     for (int i=0; i<9; ++i) p[i] = i;
  30.  
  31.     for (int i=0; i<9; ++i) visit[i] = false;
  32.     DFS(0);
  33.  
  34.     int x, y;
  35.     while (cin >> x >> y)
  36.         cout << "" << lca[x][y];
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement