思路:
由题意求最多的花费的路费,相当于是求树的直径,树的直径则为最大值
,另外由于是稀疏图,所以用邻接表来存储
代码:
# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
# include<vector>
using namespace std;
const int N = 100010;
struct Edge
{
int id,w;
};
int n;
vector<Edge> h[N];
int dis[N];
void dfs(int u,int father,int distance)
{
dis[u] = distance;
for(auto node : h[u])//遍历该节点的所有儿子
{
if(node.id != father)//防止往回走
{
dfs(node.id,u,distance + node.w);
}
}
}
int main()
{
scanf("%d",&n);
for(int i = 0;i < n;i++)
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
h[a].push_back({b,c});
h[b].push_back({a,c});
}
dfs(1,-1,0);
int u = 1;
for(int i = 1;i <= n;i++)
{
if(dis[i] > dis[u])
{
u = i;
}
}
dfs(u,-1,0);
for(int i = 1;i <= n;i++)
{
if(dis[i] > dis[u])
{
u = i;
}
}
int s = dis[u];
printf("%lld\n",10 * s + s * (s + 1ll) / 2);
return 0;
}