-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy path33_oliver_and_the_game.cpp
98 lines (83 loc) · 2.36 KB
/
33_oliver_and_the_game.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
link: https://www.hackerearth.com/practice/algorithms/graphs/topological-sort/practice-problems/algorithm/oliver-and-the-game-3/
video: https://youtu.be/5h1JYjin_4o
euler tour: https://www.geeksforgeeks.org/euler-tour-tree/
here in this problem we can do just 2 things either go towards the mantion or away from the mantion
not both.
*/
// ----------------------------------------------------------------------------------------------------------------------- //
#include<bits/stdc++.h>
#define int long long int
#define pb push_back
#define ps(x,y) fixed<<setprecision(y)<<x
#define mod 1000000007
#define w(x) int x; cin>>x; while(x--)
using namespace std;
vector<int> inTime;
vector<int> outTime;
int timer = 1;
void resize(int n) {
inTime.resize(n + 1);
outTime.resize(n + 1);
}
void dfs(int src, int par, vector<int> g[]) {
inTime[src] = timer++;
for (auto x : g[src]) {
if (x != par) {
dfs(x, src, g);
}
}
outTime[src] = timer++;
}
// is x in sub-tree of y
bool check(int x, int y) {
if (inTime[x] > inTime[y] and outTime[x] < outTime[y])
return true;
return false;
}
int32_t main() {
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int n;
cin >> n;
timer = 1;
resize(n);
vector<int> g[n + 1];
for (int i = 0;i < n - 1;i++) {
int x, y;
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
dfs(1, 0, g);
int q;
cin >> q;
for (int i = 0;i < q;i++) {
int type, x, y;
cin >> type >> x >> y;
if (!check(x, y) and !check(y, x)) {
cout << "NO\n";
continue;
}
if (type == 0) {
/*
means we have to go towards the mantion
hence check if y is in sub-tree of x. (as it is)
*/
if (check(y, x))
cout << "YES\n";
else
cout << "NO\n";
}
else if (type == 1) {
/*
means we have to go away from the mantion
hence check if x is in sub-tree of y. (just swap the x and y to reuse the func.)
*/
if (check(x, y))
cout << "YES\n";
else
cout << "NO\n";
}
}
return 0;
}