-
Notifications
You must be signed in to change notification settings - Fork 0
/
C. Anji's Binary Tree.cpp
79 lines (58 loc) · 1.31 KB
/
C. Anji's Binary Tree.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
#include <bits/stdc++.h>
using namespace std;
#define int long long
signed main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
string s;
cin >> s;
vector<int> l(n), r(n);
for (int i = 0; i < n; i++)
cin >> l[i] >> r[i];
vector<int> ans(n);
vector<int> ll(n, -1), rr(n, -1);
for (int i = 0; i < n; i++)
{
if (l[i] == 0 && r[i] == 0)
ans[i] = 0;
else
ans[i] = 1e9;
if (l[i])
ll[l[i] - 1] = i;
if (r[i])
rr[r[i] - 1] = i;
}
set<pair<int, int>> sp;
for (int i = 0; i < n; i++)
sp.insert({ans[i], i});
while (sp.size())
{
auto x = *sp.begin();
sp.erase(sp.begin());
if (x.first > ans[x.second])
continue;
if (ll[x.second] != -1)
{
if (ans[ll[x.second]] > x.first + (s[ll[x.second]] != 'L'))
{
ans[ll[x.second]] = x.first + (s[ll[x.second]] != 'L');
sp.insert({ans[ll[x.second]], ll[x.second]});
}
}
if (rr[x.second] != -1)
{
if (ans[rr[x.second]] > x.first + (s[rr[x.second]] != 'R'))
{
ans[rr[x.second]] = x.first + (s[rr[x.second]] != 'R');
sp.insert({ans[rr[x.second]], rr[x.second]});
}
}
}
cout << ans[0] << "\n";
}
}