2.树的最长路径
给定一棵树,树中包含 n 个结点(编号1~n)和 n−1 条无向边,每条边都有一个权值。
现在请你找到树中的一条最长路径。
换句话说,要找到一条路径,使得使得路径两端的点的距离最远。
注意:路径中可以只包含一个点。
输入格式
第一行包含整数 n。
接下来 n−1 行,每行包含三个整数
a
i
,
b
i
,
c
i
,
a_i,b_i,c_i,
ai,bi,ci,表示点
a
i
和
b
i
a_i和b_i
ai和bi之间存在一条权值为
c
i
c_i
ci 的边。
输出格式
输出一个整数,表示树的最长路径的长度。
数据范围
1 ≤ n ≤ 10000 , 1 ≤ a i , b i ≤ n , − 105 ≤ c i ≤ 105 1≤n≤10000, \\ 1≤ai,bi≤n, \\ −105≤ci≤105 1≤n≤10000,1≤ai,bi≤n,−105≤ci≤105
输入样例:
6
5 1 6
1 4 5
6 3 9
2 6 8
6 1 7
输出样例:
22
链式前向星版
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10005;
int n, f1[N], f2[N] , res = 0;//f1表示最长路径,f2表示次长路径
int head[N], cnt = 0;
struct edge{
int next, to, dis;
}e[N << 1];
void addedge(int u, int v , int w) {
e[++cnt].next = head[u]; // 当前边的后继
e[cnt].to = v; // 当前边的终点
e[cnt].dis = w;
head[u] = cnt ;
}
void dfs(int u ,int last){
for (int i = head[u]; i; i = e[i].next ){
int v = e[i].to;
if(v == last) continue;
dfs(v, u);
if(f1[v] + e[i].dis >= f1[u]) f2[u] = f1[u] , f1[u] = f1[v] + e[i].dis;//最长路径转移
else if(f1[v] + e[i].dis > f2[u]) f2[u] = f1[v] + e[i].dis;//次长路径转移
}
res = max(res , f1[u] + f2[u]);
}
int main() {
scanf("%d", &n);
for (int i = 1, u, v, w; i < n; i++) {
scanf("%d%d%d", &u, &v, &w);
addedge(u, v, w); addedge(v, u, w);
}
dfs(1, 0);
printf("%d\n", res);
return 0;
}
vector版
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 40005;
int n, f[N][2] , res = 0;//f[i][0] 表示以i为端点的某最长路径 ,f[i][1] 表示以i为端点的某次长路径
struct node{
int to, dis;
};
vector<node> edge[N];
void read(){
cin >> n;
for (int i = 1 , a , b , c; i < n; i ++ ){
f[i][0] = f[i][1] = 0;
cin >> a >> b >> c;
edge[a].push_back((node){b,c});
edge[b].push_back((node){a,c});
}
return ;
}
void dfs(int u ,int last){
for (int i = 0 , j , v; i < edge[u].size(); i ++ ){
if(edge[u][i].to == last) continue;//不能递归父节点
dfs(edge[u][i].to , u);//根节点变为子节点
j = edge[u][i].to , v = edge[u][i].dis;
if(f[j][0] + v >= f[u][0]) f[u][1] = f[u][0] , f[u][0] = f[j][0] + v;//把当前最长路径变为次长路径,并更新f[u][0]
else if (f[j][0] + v > f[u][1]) f[u][1] = f[j][0] + v;//更新 f[u][1]
}
res = max(res, f[u][0]+ f[u][1]);
return ;
}
int main() {
read();
dfs(1, 0);
printf("%d\n", res);
return 0;
}