이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ii pair<int, int>
#define iii pair<ii, int>
#define mp make_pair
#define eb emplace_back
#define vi vector<int>
#define vii vector<ii>
#define viii vector<iii>
#define fi first
#define se second
#define xx fi.fi
#define yy fi.se
#define zz se
int n, ans, mxw[200005][2], dp[200005][2], pw[200005], p[200005];
vii G[200005];
void dfs(int u)
{
int mxr = LLONG_MIN/100LL;
for(ii e: G[u])
{
int v = e.fi, w = e.se;
if(v!=p[u])
{
p[v] = u;
pw[v] = w;
dfs(v);
dp[u][0]+=dp[v][1];
int replace = dp[v][0] - dp[v][1] + w;
mxr = max(mxr, replace);
int temp = mxw[u][0], mx0 = mxw[u][0], mx1 = mxw[u][1];
if(!mx0 or replace>dp[mx0][0] - dp[mx0][1] + pw[mx0])
{
mxw[u][1] = mxw[u][0];
mxw[u][0] = v;
}
else if(!mx1 or replace> dp[mx1][0] - dp[mx1][1] + pw[mx1])
{
mxw[u][1] = v;
}
}
}
dp[u][1] = max(dp[u][0], (u==1? LLONG_MIN/100LL: pw[u] + mxr + dp[u][0])); //toi quen th u = 1 ditme
// cout<<u<<" "<<dp[u][0]<<" "<<dp[u][1]<<endl;
}
void euler(int u)
{
ans = max(ans, dp[u][0]);
for(ii e: G[u])
{
int v = e.fi, w = e.se;
if(v!=p[u])
{
// reroot
int tu0 = dp[u][0], tu1 = dp[u][1], tv0 = dp[v][0], tv1 = dp[v][1];
int mxid = mxw[u][0]==v? mxw[u][1]: mxw[u][0];
int mx = max((!mxid? LLONG_MIN/100ll: dp[mxid][0] - dp[mxid][1] + pw[mxid]), (!p[u]? LLONG_MIN/100LL: dp[p[u]][0] - dp[p[u]][1] + pw[u])); // toi quen truong hop mxid = 0 ditme
dp[u][0] = dp[u][0] - dp[v][1];
dp[u][1] = max(dp[u][0], dp[u][0] + mx + w);
dp[v][0] = dp[v][1] = dp[v][0]+dp[u][1];
// cout<<mx<<endl;
// cout<<u<<" "<<v<<" "<<dp[u][0]<<" "<<dp[u][1]<<" "<<dp[v][1]<<endl;
euler(v);
//rollback
dp[u][0] = tu0, dp[u][1] = tu1, dp[v][0] = tv0, dp[v][1] = tv1;
}
}
}
signed main()
{
// freopen(".inp", "r", stdin);
// freopen(".out", "w", stdout);
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
// cout.tie(NULL);
cin>>n;
for(int i=1; i<=n-1; i++)
{
int u, v, w;
cin>>u>>v>>w;
G[u].eb(v, w);
G[v].eb(u, w);
}
dfs(1);
euler(1);
cout<<ans;
}
컴파일 시 표준 에러 (stderr) 메시지
beads.cpp: In function 'void dfs(long long int)':
beads.cpp:38:8: warning: unused variable 'temp' [-Wunused-variable]
38 | int temp = mxw[u][0], mx0 = mxw[u][0], mx1 = mxw[u][1];
| ^~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |