forked from codersinghal/Competitive-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinout-dp.cpp
More file actions
29 lines (26 loc) · 645 Bytes
/
inout-dp.cpp
File metadata and controls
29 lines (26 loc) · 645 Bytes
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
// inout dp used for diameter of tree ,max sum between two nodes.
ll dfs1(ll node, ll par){
in[node] = 0LL;
for(auto child: g[node]){
if(child == par)continue;
dfs1(child, node);
in[node] = max(in[node], 1+in[child]);
}
}
// compute out[] array
ll dfs2(ll node, ll par){
ll mx1 = -1;
ll mx2 = -1;
for(auto child: g[node]){
if(child == par) continue;
if(in[child] >= mx1) mx2 = mx1, mx1 = in[child];
else if(in[child] > mx2) mx2 = in[child];
}
for(auto child: g[node]){
if(child == par) continue;
ll use = mx1;
if(mx1 == in[child]) use = mx2;
out[child] = max(1LL+out[node], 2LL+use);
dfs2(child, node);
}
}