이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
/*typedef __uint128_t L;
struct FastMod {
ull b, m;
FastMod(ull b) : b(b), m(ull((L(1) << 64) / b)) {}
ull reduce(ull a) {
ull q = (ull)((L(m) * a) >> 64);
ull r = a - q * b; // can be proven that 0 <= r < 2*b
return r >= b ? r - b : r;
}
};
FastMod FM(2);*/
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
void debug_out() { cerr << endl; }
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
cerr << " " << H;
debug_out(T...);
}
#define debug(...) cerr << "(" << #__VA_ARGS__ << "):", debug_out(__VA_ARGS__)
#define all(x) x.begin(), x.end()
#define MP(x, y) make_pair(x, y)
#define F first
#define S second
//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int maxn = 2e5 + 10;
const int inf = 2e9;
int n, dp[maxn][2][2]; // 0 ya 1 aval mitone root bezane? 0 ya 1 dovom yal parentesh khalie ya na
vector<pii> g[maxn];
void dfs(int v, int p = -1, int x = 0){
int mx = 0;
for (auto [u, w]: g[v]){
if (u != p){
dfs(u, v, w);
dp[v][0][0] += dp[u][0][1];
dp[v][0][1] += dp[u][0][1];
dp[v][1][0] += dp[u][0][1];
dp[v][1][1] += dp[u][0][1];
mx = max(mx, dp[u][1][1] - dp[u][0][1]);
}
}
dp[v][1][0] += mx;
dp[v][1][1] += mx;
if (p != -1 && g[v].size() != 1){
int tmp = x;
int mx = -inf;
for (auto [u, w]: g[v]){
if (u != p){
tmp += dp[u][0][1];
mx = max(mx, dp[u][0][0] - dp[u][0][1] + w);
}
}
dp[v][0][1] = max(dp[v][0][1], tmp + mx);
tmp = x;
mx = -inf;
for (auto [u, w]: g[v]){
if (u != p){
tmp += dp[u][0][1];
mx = max(mx, dp[u][1][0] - dp[u][0][1] + w);
}
}
dp[v][1][1] = max(dp[v][1][1], tmp + mx);
}
if ((int)g[v].size() - (p != -1) >= 2){
multiset<int> st;
int tmp = 0;
int mx = 0;
for (auto [u, w]: g[v]){
if (u != p){
tmp += dp[u][0][1];
st.insert(dp[u][0][0] - dp[u][0][1] + w);
}
}
for (auto [u, w]: g[v]){
if (u != p){
st.erase(st.find(dp[u][0][0] - dp[u][0][1] + w));
auto it = st.end();
it--;
int x = *it;
mx = max(mx, tmp + x + dp[u][1][0] - dp[u][0][1] + w);
st.insert(dp[u][0][0] - dp[u][0][1] + w);
}
}
dp[v][1][0] = max(dp[v][1][0], mx);
dp[v][1][1] = max(dp[v][1][1], mx);
}
}
int main(){
ios_base::sync_with_stdio(false); cin.tie(0);
cin >> n;
for (int i = 1; i < n; i++){
int u, v, w; cin >> u >> v >> w;
g[u].push_back({v, w});
g[v].push_back({u, w});
}
dfs(1);
cout << dp[1][1][0] << '\n';
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... |