通过题目描述我们可以清楚,如果要找到最大消费,我们就需要找到最长的边,而对于最长的边,我们需要进行dfs,从王国出发,开始寻找最长边,最后寻找到最长边进行高斯求和即可
上代码
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<unordered_map>
using namespace std;
struct Node{
int value;
vector <Node*> children;//存储子节点
vector <int> length;//存储路径长度
};
int n;
unordered_map <int,Node*> mp;
bool *st;
int res;
int dfs(int x, int fa)//分别表示访问到了哪个结点,父节点
{
int dist = 0;//返回最长链
int d1 = 0, d2 = 0;//返回最长链和次长链
for(int i = 0; i < mp[x]->children.size(); i++){
Node* node1 = mp[x]->children[i];
if(node1->value == fa) continue;//如果当前子节点是父节点,直接跳过
int d = dfs(node1->value, x) + mp[x]->length[i];//当前节点最长就是其子节点中最长的数值
if(d > d1){//如果当前链长大于最长链长,就分别更新最长链长和次长链
d2 = d1;
d1 = d;
}
else if(d > d2) d2 = d;//如果只大于次长链就只更新次长链
dist = max(dist, d);//当前最长链
}
res = max(res, d1 + d2);
return dist;
}
int main(void)
{
cin >> n;
Node node[n + 10];
st = new bool[n + 10];
memset(st, 0, sizeof(st));
for(int i = 1; i <= n; i++){
node[i].value = i;
mp[i] = &node[i];
}
for(int i = 1; i <= n - 1; i++){
int x, y, z; cin >> x >> y >> z;
mp[x]->children.push_back(mp[y]);
mp[y]->children.push_back(mp[x]);
mp[x]->length.push_back(z);
mp[y]->length.push_back(z);
}
dfs(1, -1);
cout << 10 * res + (res + 1) * res / 2 << endl;
return 0;
}