This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int MAXN = 2e5 + 10;
#define debug(...) fprintf(stderr, __VA_ARGS__)
#define fi first
#define se second
#define all(v) (v).begin(), (v).end()
#define fillchar(a, s) memset((a), (s), sizeof(a))
void setmax (int &a, int b) {
if (a < b) {
a = b;
}
}
int N;
vector<int> adj[MAXN];
map<int, int> weight[MAXN];
int W[MAXN];
int dp[MAXN][2];
void dfs (int x) {
int totc = 0;
for (int y : adj[x]) {
adj[y].erase(find(all(adj[y]), x));
W[y] = weight[x][y];
dfs(y);
totc += dp[y][0];
}
vector<int> vals;
for (int y : adj[x]) {
vals.push_back(W[y] + dp[y][1] - dp[y][0]);
}
dp[x][1] = totc;
if (vals.size() >= 2) {
iter_swap(max_element(all(vals)), vals.begin());
iter_swap(max_element(vals.begin() + 1, vals.end()), vals.begin() + 1);
setmax(dp[x][1], vals[0] + vals[1] + totc);
}
dp[x][0] = totc;
vals.clear();
for (int y : adj[x]) {
//debug("equis x = %d. Va %d\n", x, W[y] + W[x]);
vals.push_back(W[y] + W[x] + dp[y][1] - dp[y][0]);
}
if (!vals.empty()) {
setmax(dp[x][0], totc + *max_element(all(vals)));
}
//debug("dp[%d][%d] = %d, dp[%d][%d] = %d\n", x, 1, dp[x][1], x, 0, dp[x][0]);
}
int main() {
scanf("%d", &N);
for (int i = 1; i < N; i++) {
int a, b, w;
scanf("%d %d %d", &a, &b, &w);
adj[a].push_back(b);
adj[b].push_back(a);
weight[a][b] = weight[b][a] = w;
}
dfs(1);
printf("%d\n", dp[1][1]);
}
Compilation message (stderr)
beads.cpp: In function 'int main()':
beads.cpp:64:7: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
scanf("%d", &N);
~~~~~^~~~~~~~~~
beads.cpp:67:8: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
scanf("%d %d %d", &a, &b, &w);
~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
# | 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... |