Skip to content

Commit 078bdd5

Browse files
Create Parsa and Humungous Tree.cpp
1 parent 1f6e324 commit 078bdd5

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <algorithm>
4+
5+
using namespace std;
6+
7+
const int MAX_N = 1e5 + 5, MAX_ENDS = 2, L = 0, R = 1;
8+
vector <int> tree[MAX_N];
9+
long long maximum_at[MAX_N][MAX_ENDS], left_value[MAX_N], right_value[MAX_N];
10+
11+
void initialize(int no_of_vertices)
12+
{
13+
for(int i = 1; i <= no_of_vertices; i++)
14+
{
15+
tree[i].clear();
16+
maximum_at[i][L] = maximum_at[i][R] = 0;
17+
}
18+
}
19+
20+
void dfs(int v, int parent_v)
21+
{
22+
for(int child_v : tree[v])
23+
{
24+
if(child_v == parent_v)
25+
{
26+
continue;
27+
}
28+
29+
dfs(child_v, v);
30+
31+
long long using_left_value_at_child = abs(left_value[v] - left_value[child_v]) + maximum_at[child_v][L];
32+
long long using_right_value_at_child = abs(left_value[v] - right_value[child_v]) + maximum_at[child_v][R];
33+
34+
maximum_at[v][L] += max(using_left_value_at_child, using_right_value_at_child);
35+
36+
using_left_value_at_child = abs(right_value[v] - left_value[child_v]) + maximum_at[child_v][L];
37+
using_right_value_at_child = abs(right_value[v] - right_value[child_v]) + maximum_at[child_v][R];
38+
39+
maximum_at[v][R] += max(using_left_value_at_child, using_right_value_at_child);
40+
}
41+
42+
/*cout << "At " << v << " L = " << left_value[v] << " Maximum = " << maximum_at[v][L] << "\n";
43+
cout << "At " << v << " R = " << right_value[v] << " Maximum = " << maximum_at[v][R] << "\n";*/
44+
}
45+
46+
void solve()
47+
{
48+
int no_of_vertices;
49+
cin >> no_of_vertices;
50+
51+
initialize(no_of_vertices);
52+
53+
for(int i = 1; i <= no_of_vertices; i++)
54+
{
55+
cin >> left_value[i] >> right_value[i];
56+
}
57+
58+
int no_of_edges = no_of_vertices - 1;
59+
for(int i = 1; i <= no_of_edges; i++)
60+
{
61+
int u, v;
62+
cin >> u >> v;
63+
64+
tree[u].push_back(v);
65+
tree[v].push_back(u);
66+
}
67+
68+
dfs(1, 0);
69+
70+
cout << max(maximum_at[1][L], maximum_at[1][R]) << "\n";
71+
}
72+
73+
int main()
74+
{
75+
ios_base::sync_with_stdio(false);
76+
cin.tie(NULL);
77+
78+
int no_of_test_cases;
79+
cin >> no_of_test_cases;
80+
81+
while(no_of_test_cases--)
82+
solve();
83+
84+
return 0;
85+
}

0 commit comments

Comments
 (0)