Advertisement
Romanchenko

pr427

Nov 7th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4. int T;
  5.  
  6. void dfs(int v, vector<vector<int> > &g, vector<int> &used, vector<int> &tin, vector<int> &tout)
  7. {
  8.     used[v] = 1;
  9.     tin[v] = T++;
  10.     for (auto to : g[v])
  11.     {
  12.         if (!used[to])
  13.             dfs(to, g, used, tin, tout);
  14.     }
  15.     tout[v] = T++; 
  16. }
  17.  
  18. int main()
  19. {
  20.     ios_base::sync_with_stdio(false);
  21.     cin.tie(0);
  22.     //freopen("input.txt", "r", stdin);
  23.     int n;
  24.     cin >> n;
  25.     vector<vector<int> > g(n);
  26.     for (int i = 0; i < n - 1; i++)
  27.     {
  28.         int x;
  29.         cin >> x;
  30.         g[x - 1].push_back(i + 1);
  31.         g[i + 1].push_back(x - 1);
  32.     }
  33.     vector<int> tin (n ,0), tout(n, 0);
  34.     T = 0;
  35.     vector<int> used (n, 0);
  36.     dfs(0, g, used, tin, tout);
  37.     int m;
  38.     cin >> m;
  39.  
  40.     for (int i = 0; i < m; i++)
  41.     {
  42.         int u, v;
  43.         cin >> u >> v;
  44.         u--, v--;
  45.         if (tin[u] < tin[v] && tout[u] > tout[v])
  46.             cout << 1 << endl;
  47.         else if (tin[u] > tin[v] && tout[u] < tout[v])
  48.             cout << 2 << endl;
  49.         else
  50.             cout << 3 << endl;
  51.     }
  52.     return 0;  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement