#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 1;
int n;
vector<pair<int,int> > adj[N];
int dp[N][3];
void dfs(int u,int p)
{
int mx = INT_MIN,mx2 = INT_MIN,s1 = 0,ch = 0;
dp[u][1] = INT_MIN;
for(auto [d,v] : adj[u]) if(v!=p)
{
ch++;
dfs(v,u);
dp[u][0]+=max(dp[v][0],dp[v][2]);
if(dp[v][1]!=INT_MIN) s1+=dp[v][1]+d;
if(dp[v][1]!=INT_MIN) dp[u][1] = max(dp[u][1],d+max(dp[v][0],dp[v][2])-dp[v][1]-d);
else dp[u][1] = max(dp[u][1],d+max(dp[v][0],dp[v][2]));
int tmp = max(max(dp[v][0],dp[v][2]),d+dp[v][1]);
dp[u][2]+=tmp;
if(d+max(dp[v][0],dp[v][2])-tmp>mx) mx2 = mx,mx = d+max(dp[v][0],dp[v][2])-tmp;
else if(d+max(dp[v][0],dp[v][2])-tmp>mx2) mx2 = d+max(dp[v][0],dp[v][2])-tmp;
}
dp[u][1]+=s1;
if(ch>=2) dp[u][2]+=max(0,mx+mx2);
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> n;
for(int i = 0;i < n-1;i++)
{
int a,b,d;
cin >> a >> b >> d;
adj[a].push_back({d,b});
adj[b].push_back({d,a});
}
dfs(1,0);
cout << max(dp[1][0],dp[1][2]);
}
Compilation message
beads.cpp: In function 'void dfs(int, int)':
beads.cpp:14:14: warning: decomposition declaration only available with -std=c++1z or -std=gnu++1z
for(auto [d,v] : adj[u]) if(v!=p)
^
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
8 ms |
5248 KB |
Output is correct |
2 |
Correct |
7 ms |
5120 KB |
Output is correct |
3 |
Correct |
7 ms |
4992 KB |
Output is correct |
4 |
Correct |
7 ms |
4992 KB |
Output is correct |
5 |
Correct |
7 ms |
4992 KB |
Output is correct |
6 |
Incorrect |
7 ms |
4992 KB |
Output isn't correct |
7 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
8 ms |
5248 KB |
Output is correct |
2 |
Correct |
7 ms |
5120 KB |
Output is correct |
3 |
Correct |
7 ms |
4992 KB |
Output is correct |
4 |
Correct |
7 ms |
4992 KB |
Output is correct |
5 |
Correct |
7 ms |
4992 KB |
Output is correct |
6 |
Incorrect |
7 ms |
4992 KB |
Output isn't correct |
7 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
8 ms |
5248 KB |
Output is correct |
2 |
Correct |
7 ms |
5120 KB |
Output is correct |
3 |
Correct |
7 ms |
4992 KB |
Output is correct |
4 |
Correct |
7 ms |
4992 KB |
Output is correct |
5 |
Correct |
7 ms |
4992 KB |
Output is correct |
6 |
Incorrect |
7 ms |
4992 KB |
Output isn't correct |
7 |
Halted |
0 ms |
0 KB |
- |
# |
Verdict |
Execution time |
Memory |
Grader output |
1 |
Correct |
8 ms |
5248 KB |
Output is correct |
2 |
Correct |
7 ms |
5120 KB |
Output is correct |
3 |
Correct |
7 ms |
4992 KB |
Output is correct |
4 |
Correct |
7 ms |
4992 KB |
Output is correct |
5 |
Correct |
7 ms |
4992 KB |
Output is correct |
6 |
Incorrect |
7 ms |
4992 KB |
Output isn't correct |
7 |
Halted |
0 ms |
0 KB |
- |