@@ -83,13 +83,13 @@ long long mx_beauty(int u, int v, bool type) {
83
83
}
84
84
}
85
85
86
- void dfs (int u, int par) {
86
+ void calculate_dp (int u, int par) {
87
87
for (int v : adj [u ]) {
88
88
if (v == par ) {
89
89
continue ;
90
90
}
91
91
92
- dfs (v , u );
92
+ calculate_dp (v , u );
93
93
dp[u ][0 ] += mx_beauty(u, v, 0);
94
94
dp[u ][1 ] += mx_beauty(u, v, 1);
95
95
}
@@ -126,11 +126,92 @@ int main() {
126
126
adj [v ].push_back (u );
127
127
}
128
128
129
- dfs (0 , - 1 );
129
+ calculate_dp (0 , - 1 );
130
130
131
131
cout << std ::max (dp [0 ][0 ], dp [0 ][1 ]) << endl ;
132
132
}
133
133
}
134
134
` ` `
135
135
</CPPSection>
136
+
137
+ <JavaSection>
138
+ ` ` ` java
139
+ import java .io .* ;
140
+ import java .util .* ;
141
+
142
+ public class ParsasHumongousTree {
143
+ private static List < List < Integer >> adj = new ArrayList <> ();
144
+ private static int [] l, r;
145
+ private static long [][] dp;
146
+
147
+ public static void main(String [] args ) {
148
+ Kattio io = new Kattio ();
149
+ int t = io .nextInt ();
150
+
151
+ for (int tc = 0 ; tc < t ; tc ++ ) {
152
+ int n = io .nextInt ();
153
+
154
+ l = new int [n + 1 ];
155
+ r = new int [n + 1 ];
156
+ dp = new long [n + 1 ][2 ];
157
+ adj .clear ();
158
+
159
+ for (int i = 1 ; i <= n ; i ++ ) {
160
+ l [i ] = io .nextInt ();
161
+ r [i ] = io .nextInt ();
162
+ }
163
+
164
+ for (int i = 0 ; i <= n ; i ++ ) {
165
+ adj .add (new ArrayList <> ());
166
+ }
167
+
168
+ for (int i = 0 ; i < n - 1 ; i ++ ) {
169
+ int u = io .nextInt (), v = io .nextInt ();
170
+ adj .get (u ).add (v );
171
+ adj .get (v ).add (u );
172
+ }
173
+
174
+ calculateDP (1 , - 1 );
175
+
176
+ io .println (Math .max (dp [1 ][0 ], dp [1 ][1 ]));
177
+ }
178
+
179
+ io .flush ();
180
+ }
181
+
182
+ private static void calculateDP(int u , int par ) {
183
+ for (int v : adj .get (u )) {
184
+ // Continue if `v` is `u`'s parent.
185
+ if (v == par ) {
186
+ continue ;
187
+ }
188
+
189
+ // Calculate the DP values for 'v'.
190
+ calculateDP (v , u );
191
+
192
+ // DP transitions for 'u'.
193
+ dp [u ][0 ] += maxBeauty (u , v , false );
194
+ dp [u ][1 ] += maxBeauty (u , v , true );
195
+ }
196
+ }
197
+
198
+ // Return optimal beauty value for vertex u with subtree v.
199
+ private static long maxBeauty(int u , int v , boolean type ) {
200
+ if (! type ) {
201
+ long swtch = dp [v ][1 ] + Math .abs (l [u ] - r [v ]);
202
+ long sm = dp [v ][0 ] + Math .abs (l [u ] - l [v ]);
203
+
204
+ return Math .max (swtch , sm );
205
+ } else {
206
+ long swtch = dp [v ][1 ] + Math .abs (r [u ] - r [v ]);
207
+ long sm = dp [v ][0 ] + Math .abs (r [u ] - l [v ]);
208
+
209
+ return Math .max (swtch , sm );
210
+ }
211
+ }
212
+
213
+ // CodeSnip{Kattio}
214
+ }
215
+ ` ` `
216
+ </JavaSection>
136
217
</LanguageSection>
0 commit comments