Title

树的的直径(两遍DFS可行性的证明)


AcWing 1207.大臣的旅费

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5+10,M=2e5+20;

ll dist[N];

int h[M],ne[M],e[M],w[M],idx;
void add(int a,int b,int c)
{
	e[idx]=b,ne[idx]=h[a],w[idx]=c,h[a]=idx++;
}


void dfs(int st,int father,ll distance)
{
    dist[st] = distance;
    for(int i = h[st];~i;i=ne[i])
    	if(e[i]!=father) dfs(e[i],st,dist[st]+w[i]);
}

ll cal(ll k)
{
     return k*10+(k+1ll)*k/2;	
}

int main()
{
	memset(h,-1,sizeof(h));
	int A,B,C;
    int n;
    cin>>n;
	for(int i=0;i<n-1;i++)
	{
		cin>>A>>B>>C;
		add(A,B,C);add(B,A,C);
	}
	
	memset(dist,0,sizeof(dist));
	dfs(1,-1,0);
	int u=1;
	for(int i=2;i<=n;i++)
	     if(dist[i]>dist[u])u=i;
	
	dfs(u,-1,0);
	ll kio=dist[1];
	for(int i=2;i<=n;i++)
	   if(dist[i]>kio)kio=dist[i];
	   
	cout<<kio*10+kio*(kio+1)/2;
	return 0;
}
posted @ 2021-07-17 11:18  BeautifulWater  阅读(102)  评论(0编辑  收藏  举报