解析:分析易得走过的路中至多存在一个分叉,则维护每个结点接下来的路的最大值与次大值然后相加即可。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define int long long
const int MAXN = 100005;
vector<pair<int, int>> tree[MAXN];
int dp[MAXN];
int max_single[MAXN];
int n;void dfs(int node, int parent) {max_single[node] = 0;int top_two[2] = {0, 0};for (auto &edge : tree[node]) {int neighbor = edge.first;int weight = edge.second;if (neighbor == parent) continue;dfs(neighbor, node);max_single[node] = max(max_single[node], max_single[neighbor] + weight);int path_sum = max_single[neighbor] + weight;if (path_sum > top_two[0]) {top_two[1] = top_two[0];top_two[0] = path_sum;} else if (path_sum > top_two[1]) {top_two[1] = path_sum;}}dp[node] = top_two[0] + top_two[1];
}signed main() {cin >> n;for (int i = 0; i < n - 1; ++i) {int u, v, w;cin >> u >> v >> w;tree[u].emplace_back(v, w);tree[v].emplace_back(u, w);}dfs(1, -1);int result = *max_element(dp + 1, dp + n + 1);cout << result << endl;return 0;
}