Advertisement
Guest User

Untitled

a guest
Aug 7th, 2017
589
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. #include <fstream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. const int N = 100010;
  6. const int M = 2000010;
  7.  
  8. ifstream F("lca.in");
  9. ofstream G("lca.out");
  10.  
  11. int n, m, dad[N], ancestor[N], lvl[N];
  12. bool black[N];
  13. int ans[M];
  14.  
  15. vector<int> v[N];
  16.  
  17. #define y first
  18. #define ord second
  19. vector<pair<int, int> > w[N];
  20.  
  21. int find(int x) {
  22. if (dad[x] != x) {
  23. dad[x] = find(dad[x]);
  24. }
  25. return dad[x];
  26. }
  27.  
  28. void union2(int x, int y) {
  29. x = find(x);
  30. y = find(y);
  31. if (lvl[x] > lvl[y]) {
  32. dad[y] = x;
  33. } else {
  34. dad[x] = y;
  35. if (lvl[x] == lvl[y]) {
  36. lvl[x]++;
  37. }
  38. }
  39. }
  40.  
  41. void lca(int x) {
  42. dad[x] = x;
  43. lvl[x] = 0;
  44. ancestor[x] = x;
  45.  
  46. for (int y : v[x]) {
  47. lca(y);
  48. union2(x, y);
  49. ancestor[find(x)] = x;
  50. }
  51.  
  52. black[x] = 1;
  53. for (pair<int, int> p : w[x]) {
  54. if (black[p.y]) {
  55. ans[p.ord] = ancestor[find(p.y)];
  56. }
  57. }
  58. }
  59.  
  60. int main() {
  61. F >> n >> m;
  62. for (int y = 2, x; y <= n; ++y) {
  63. F >> x;
  64. v[x].push_back(y);
  65. }
  66.  
  67. for (int i = 1, x, y; i <= m; ++i) {
  68. F >> x >> y;
  69. w[x].push_back(make_pair(y, i));
  70. w[y].push_back(make_pair(x, i));
  71. }
  72.  
  73. lca(1);
  74.  
  75. for (int i = 1; i <= m; ++i) {
  76. G << ans[i] << '\n';
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement