이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstdio>
#include <iomanip>
#include <fstream>
#include <cassert>
#include <cstring>
#include <unordered_set>
#include <unordered_map>
#include <numeric>
#include <ctime>
#include <bitset>
#include <complex>
#include <chrono>
#include <random>
#include <functional>
using namespace std;
#define int long long
const int INF = 1e18 + 239;
const int N = 2e5 + 7;
int to[N];
int dp[N][2];
vector<pair<int, int>> g[N];
void dfs(int cur, int p) {
vector<int> sons;
for (auto [t, w] : g[cur]) {
if (t != p) {
to[t] = w;
sons.push_back(t);
dfs(t, cur);
}
}
if (sons.empty()) {
dp[cur][0] = 0;
dp[cur][1] = -INF;
return;
}
dp[cur][0] = -INF;
dp[cur][1] = -INF;
sort(sons.begin(), sons.end(), [&](int f, int s) {
return (dp[f][0] + to[f]) - max(dp[f][0], dp[f][1]) > (dp[s][0] + to[s]) - max(dp[s][0], dp[s][1]);
});
//
{
int c = dp[sons[0]][0] + to[sons[0]] + to[cur];
for (int i = 1; i < (int)sons.size(); i++) {
c += max(dp[sons[i]][0], dp[sons[i]][1]);
}
dp[cur][1] = max(dp[cur][1], c);
}
//
{
int c = 0;
for (auto u : sons) {
c += max(dp[u][0], dp[u][1]);
}
dp[cur][0] = max(dp[cur][0], c);
}
//
if (sons.size() > 1) {
int c = dp[sons[0]][0] + dp[sons[1]][0] + to[sons[0]] + to[sons[1]];
for (int i = 2; i < (int)sons.size(); i++) {
c += max(dp[sons[i]][0], dp[sons[i]][1]);
}
dp[cur][0] = max(dp[cur][0], c);
}
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i + 1 < n; i++) {
int u, v, w;
cin >> u >> v >> w;
u--;
v--;
g[u].push_back({v, w});
g[v].push_back({u, w});
}
dfs(0, -1);
cout << dp[0][0] << '\n';
}
# | 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... |