定义:树上距离最远的两点间的距离
性质:
1.对于树上的任意一点,树上与它距离最远的点一定为树的直径的两个端点之一
2.直径两端点一定是两个叶子节点
3.对于两棵树,如果第一棵树的直径两端点为(u,v),(u,v),(u,v),第二棵树直径两端点为(x,y),(x,y),(x,y),用一条边将两棵树连接,那么新树的直径的两端点一定是u,v,x,yu,v,x,yu,v,x,y中的两个点
4.对于一棵树,如果在一个点上连接一个叶子节点,那么最多会改变直径的一个端点
5.若一棵树存在多条直径,那么这些直径交于一点且交点是这些直径的中点
1.两遍dfs
#include <bits/stdc++.h>
using namespace std;
static auto speedup = []() {ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return nullptr; }();
const int maxn = 3e5 + 7;
int dis[maxn];
vector<int> e[maxn];
void dfs(int x,int fa,int &maxId) {
dis[x] = dis[fa] + 1;
if (dis[x] > dis[maxId]) {
maxId = x;
}
for (auto& nx : e[x]) {
if (nx == fa)continue;
dfs(nx, x, maxId);
}
}
int getTreeDiam(int x) {
int y = x;
dfs(x, 0,y);
x = y;
dfs(x, 0,y);
return dis[y];
}
2.dp
int dp(int x,int fa) {
int cur = 0;
for (auto& nx : e[x]) {
if (nx == fa)continue;
int ret = dp(nx, x);
treelen = max(treelen, cur + ret + 1);
cur = max(cur, ret + 1);
}
return cur;
}
int getTreeDiam2(int x) {
treelen = 0;
dp(x,0);
return treelen;
}