이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
#define f first
#define s second
const int N = 2e5 + 100;
const ll mod = 998244353;
const ll inf = 1e9 + 100;
ll dp[4][N], par[N], ans = 0, e[N];
vector<pair<ll, ll>> adj[N];
multiset<ll, greater<ll>> st[N];
int n;
inline void upd(int u)
{
dp[1][u] = dp[0][u];
if(st[u].size() > 0)
{
ll w = *(st[u].begin());
dp[1][u] += max(0ll, w + e[u]);
}
}
void dfs(int u)
{
for(auto it : adj[u])
{
int x = it.f;
ll w = it.s;
if(x != par[u])
{
par[x] = u;
e[x] = w;
dfs(x);
dp[0][u] += dp[1][x];
st[u].insert(dp[0][x] - dp[1][x] + e[x]);
}
}
upd(u);
//cout << u << ' ' << dp[1][u] << ' ' << dp[2][u] << endl;
}
inline void move_root(int x, int u, ll w)
{
dp[0][x] -= dp[1][u];
st[x].erase(st[x].find(dp[0][u]-dp[1][u]+w));
e[x] = w;
upd(x);
dp[0][u] += dp[1][x];
e[u] = 0;
st[u].insert(dp[0][x]-dp[1][x]+e[x]);
upd(u);
}
void DFS(int u)
{
ans = max(ans, dp[0][u]);
for(auto it : adj[u])
{
int x = it.f;
ll w = it.s;
if(x == par[u])
continue;
move_root(u, x, w);
DFS(x);
move_root(x, u, w);
}
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n;
for(int i = 0; i < n-1; i++)
{
int x, y;
ll w;
cin >> x >> y >> w;
x--; y--;
adj[x].push_back({y, w});
adj[y].push_back({x, w});
}
dfs(0);
DFS(0);
cout << ans << endl;
return 0;
}
# | 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... |