知识要点:树的直径
树的直径指的是树的路径最长的长度,我们要求这棵树的直径时,只要这棵树的边权都是非负的,我们就可以开始使用dfs求这个树的直径。
我们可以先遍历所有的起点,每个起点都做一次dfs,然后求最大值,这个值就是树的直径。
时间复杂度为,很显然在大数据的情况下会超时,我们不放先从起点开始,先找到从一开始路径最长的那个点,然后从那个点开始作为起点,只要一次dfs就可以了,在大数据的情况下可以通过。
代码实现:
void dfs(int x,int fa,int step){
if(step > maxx) maxx = step,id = x;
for(auto v:G[x]){
if(v != fa) dfs(v,x,step+1);
}
}homework~
P8602 [蓝桥杯 2013 省 A] 大臣的旅费
AC代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"
#define pait pair<int,int>
const int N = 1e5+7;
const int Mod = 998244353;
int n,maxx = 0,id = 0;
struct node{
int to,w;
};
vector<node>G[N];
void dfs(int x,int fa,int step){
if(step > maxx) maxx = step,id = x;
for(auto v:G[x]){
if(v.to != fa) dfs(v.to,x,step+v.w);
}
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin>>n;
for(int i=1;i<=n-1;++i){
int u,v,w; cin>>u>>v>>w;
G[u].push_back({v,w});
G[v].push_back({u,w});
}
dfs(1,0,0);
maxx = 0;
dfs(id,0,0);
cout<<maxx*10+(maxx+1)*maxx/2<<endl;
return 0;
}