树的直径
- 任取一点x
- 找到距x最远的一点y,y与据y最远的点之间的距离就是直径
Acwing.1207 大臣的旅费
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=100010;
int n;
int dis[N];
struct Edge{
int s,w;
};vector<Edge> h[N];void dfs(int start,int father,int distance){
dis[start]=distance;for(auto t:h[start])if(t.s!=father) dfs(t.s,start,distance+t.w);
}int main(){
cin>>n;int a,b,c;for(int i=1;i<n;i++){
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];cout<<s*10+s*(s+1ll)/2;return 0;
}