-
Notifications
You must be signed in to change notification settings - Fork 153
/
tree_dfs_preorder_postorder_isInSubtree.cpp
53 lines (48 loc) · 1.13 KB
/
tree_dfs_preorder_postorder_isInSubtree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Description: Preorder and Postorder stamps (Finds the preorder and postorder stamps for vertices of tree. Useful for checking if vertex is in subtree)
* Usage: preprocess O(V)
* Source: https://github.com/dragonslayerx
*/
#include <iostream>
#include <vector>
using namespace std;
const int MAX = 100005;
vector< vector<int> > T;
int prestamp[MAX], poststamp[MAX];
int counter = 0;
void preprocess(int u, int p) {
prestamp[u] = counter++;
for (int v : T[u]) {
if (v != p) {
preprocess(v, u);
}
}
poststamp[u] = counter++;
}
bool isInSubtree(int u, int v) {
return ((prestamp[u] <= prestamp[v]) && (poststamp[u] >= poststamp[v]));
}
int main() {
int n;
cin >> n;
T.resize(n);
for (int i = 0; i < n-1; i++) {
int a, b;
cin >> a >> b;
a--, b--;
T[a].push_back(b);
T[b].push_back(a);
}
int root;
cin >> root;
preprocess(root, root);
int q;
cin >> q;
while (q--) {
int u, v;
cin >> u >> v;
u--, v--;
// Check if v is in subtree of u
cout << isInSubtree(u, v) << endl;
}
}