Skip to content

Commit 5a46be7

Browse files
Merge pull request #3088 from 876pol/cf-1529c-java
update cf-1528A.mdx
2 parents 6ec96f5 + ced58c3 commit 5a46be7

File tree

1 file changed

+84
-3
lines changed

1 file changed

+84
-3
lines changed

solutions/cf-1528A.mdx

+84-3
Original file line numberDiff line numberDiff line change
@@ -83,13 +83,13 @@ long long mx_beauty(int u, int v, bool type) {
8383
}
8484
}
8585

86-
void dfs(int u, int par) {
86+
void calculate_dp(int u, int par) {
8787
for (int v : adj[u]) {
8888
if (v == par) {
8989
continue;
9090
}
9191

92-
dfs(v, u);
92+
calculate_dp(v, u);
9393
dp[u][0] += mx_beauty(u, v, 0);
9494
dp[u][1] += mx_beauty(u, v, 1);
9595
}
@@ -126,11 +126,92 @@ int main() {
126126
adj[v].push_back(u);
127127
}
128128

129-
dfs(0, -1);
129+
calculate_dp(0, -1);
130130

131131
cout << std::max(dp[0][0], dp[0][1]) << endl;
132132
}
133133
}
134134
```
135135
</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>
136217
</LanguageSection>

0 commit comments

Comments
 (0)