#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 1;
int n;
vector<pair<int,int> > adj[N];
int dp[N][4];
int mxx(int a,int b,int c){ return max(a,max(b,c)); }
void dfs(int u,int p)
{
int mx = INT_MIN,mx2 = INT_MIN,mxc = 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]+=mxx(dp[v][0],dp[v][2],dp[v][3]);
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+mxx(dp[v][0],dp[v][2],dp[v][3])-dp[v][1]-d);
else dp[u][1] = max(dp[u][1],d+mxx(dp[v][0],dp[v][2],dp[v][3]));
int tmp = max(mxx(dp[v][0],dp[v][2],dp[v][3]),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;
if(d+mxx(dp[v][3],dp[v][3],dp[v][3])-tmp>mxc) mxc = d+mxx(dp[v][3],dp[v][3],dp[v][3])-tmp;
dp[u][3]+=tmp;
}
dp[u][1]+=s1;
if(ch>=2) dp[u][3]+=mxx(0,mx+mx2,mx+mxc);
else dp[u][3] = INT_MIN;
}
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 << mxx(dp[1][0],dp[1][2],dp[1][3]);
}
Compilation message
beads.cpp: In function 'void dfs(int, int)':
beads.cpp:16:14: warning: decomposition declaration only available with -std=c++1z or -std=gnu++1z
for(auto [d,v] : adj[u]) if(v!=p)
^
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
7 ms |
5120 KB |
Output is correct |
2 |
Correct |
7 ms |
4992 KB |
Output is correct |
3 |
Correct |
7 ms |
4992 KB |
Output is correct |
4 |
Correct |
9 ms |
5120 KB |
Output is correct |
5 |
Incorrect |
7 ms |
5120 KB |
Output isn't correct |
6 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
7 ms |
5120 KB |
Output is correct |
2 |
Correct |
7 ms |
4992 KB |
Output is correct |
3 |
Correct |
7 ms |
4992 KB |
Output is correct |
4 |
Correct |
9 ms |
5120 KB |
Output is correct |
5 |
Incorrect |
7 ms |
5120 KB |
Output isn't correct |
6 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
7 ms |
5120 KB |
Output is correct |
2 |
Correct |
7 ms |
4992 KB |
Output is correct |
3 |
Correct |
7 ms |
4992 KB |
Output is correct |
4 |
Correct |
9 ms |
5120 KB |
Output is correct |
5 |
Incorrect |
7 ms |
5120 KB |
Output isn't correct |
6 |
Halted |
0 ms |
0 KB |
- |
# |
결과 |
실행 시간 |
메모리 |
Grader output |
1 |
Correct |
7 ms |
5120 KB |
Output is correct |
2 |
Correct |
7 ms |
4992 KB |
Output is correct |
3 |
Correct |
7 ms |
4992 KB |
Output is correct |
4 |
Correct |
9 ms |
5120 KB |
Output is correct |
5 |
Incorrect |
7 ms |
5120 KB |
Output isn't correct |
6 |
Halted |
0 ms |
0 KB |
- |