图论--树的直径--DFS+树形DP模板
#include <iostream>
#include <cstring>
using namespace std;
//maxv:源点能到的最远点,maxdis:最远点对应的距离,
const int maxn = 1e4 + 5;
struct Edge { int to, next, w; }edges[2 * maxn];
int head[maxn], maxdis,maxv, tot;
void add(int u, int v, int w) {
edges[tot] = { v, head[u], w };
head[u] =tot++;
}
void dfs(int u, int f, int Val) {
if (maxdis < Val){
maxdis = Val;
maxv = u;
}
for (int e = head[u]; e != -1; e = edges[e].next) {
int v = edges[e].to, w = edges[e].w;
if (v == f) continue; //父节点已经访问过,防止重复遍历,相反孩子不会重复遍历。
dfs(v, u, Val + w);
}
}
int main()
{
int e, u, v, w, s;
cin >> e;
memset(head, -1, sizeof(head));
for (int i = 1; i <= e; i++) {
cin >> u >> v >> w;
add(u, v, w), add(v, u, w);
}
dfs(1, -1, 0); //从结点1开始遍历,找到最远点maxv及对应的最远距离maxdis
maxdis = 0;
cout <<maxv<<endl;//输出直径的第一个端点
dfs(maxv, -1, 0);//从结点maxv开始遍历,找到最远点对应的距离maxdis
cout << maxdis << endl; //輸出树的直径
cout <<maxv<<endl;//输出树的直径的第二个端点
return 0;
}
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int const MAX = 100005;
int head[MAX], dp[MAX][2];
int n, s, cnt, ans;
struct EDGE
{
int v, w, next;
} e[MAX];
void Add(int u, int v, int w)
{
e[cnt].v = v;
e[cnt].w = w;
e[cnt].next = head[u];
head[u] = cnt++;
}
void DFS(int u, int fa)
{
dp[u][0] = dp[u][1] = 0;
for (int i = head[u]; i != -1; i = e[i].next)
{
int v = e[i].v;
int w = e[i].w;
if (v != fa)
{
DFS(v, u);
if (dp[u][0] < dp[v][0] + w)
{
int tmp = dp[u][0];
dp[u][0] = dp[v][0] + w;
dp[u][1] = tmp;
}
else if (dp[u][1] < dp[v][0] + w)
dp[u][1] = dp[v][0] + w;
}
}
ans = max(ans, dp[u][1] + dp[u][0]);
return;
}
int main()
{
cnt = 0;
ans = 0;
memset(head, -1, sizeof(head));
scanf("%d %d", &n, &s);
int sum = 0;
for (int i = 0; i < n - 1; i++)
{
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
Add(u, v, w);
Add(v, u, w);
sum += 2 * w;
}
DFS(s, -1);
printf("%d\n", ans);
}