



#include
#include
using namespace std;
const int N = 1e4 + 10, M = N << 1; //初始不确定树的拓扑结构,因此要建立双向边
int n;
int h[N], e[M], w[M], ne[M], idx;
int f1[N], f2[N], res;
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
void dfs(int u, int father)
{
f1[u] = f2[u] = 0;
for (int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if (j == father) continue;
dfs(j, u);
if (f1[j] + w[i] >= f1[u]) f2[u] = f1[u] ,f1[u] = f1[j] + w[i]; //最长路转移
else if (f1[j] + w[i] > f2[u]) f2[u] = f1[j] + w[i]; //次长路转移
}
res = max(res, f1[u] + f2[u]);
}
int main()
{
memset(h, -1, sizeof h);
scanf("%d", &n);
for (int i = 0; i < n - 1; i ++ )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c), add(b, a, c);
}
dfs(1, -1); //我们可以任意选取一个点作为根节点,这样整棵树的拓扑结构被唯一确定下来了
printf("%d\n", res);
return 0;
}
作者:一只野生彩色铅笔
链接:https://www.acwing.com/solution/content/63883/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
下述为添加边的具体代码
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
vector<string> letterCombinations(string d) {
unordered_map<char,string> s = {
{'2',"abc"},
{'3',"def"},
{'4',"ghi"},
{'5',"jkl"},
{'6',"mno"},
{'7',"pqrs"},
{'8',"tuv"},
{'9',"wxyz"},
};
vector<string> res,temp;
// 给你一个字符串,然后遍历其中的每一个元素,往其中添加元素
for (int i = 1; i <= d.size(); ++i) {
for (int j = 0; j < s[d[i - 1]].size(); ++j) {
// 判定是否为空的情况
if (res.size() <= s[d[i - 1]].size()){
string t;
temp.emplace_back(t+=s[d[i - 1]][j]);
}else
for (auto x : res) {
x += s[d[i - 1]][j];
temp.push_back(x);
}
res = temp;
}
}
string strs[10] = {
"","","abc","def"
,"ghi","jkl","mno"
,"pqrs","tuv","wxyz"
};
for(auto c:strs[digits[u] - '0']){
dfs(digits, u + 1,path + c); }
