题目链接:51Nod 2602 树的直径
题目大意:
题解:
两遍\(dfs\),第一遍从根开始找到最深的结点,第二遍从最深的结点开始得到树的直径。
#include <cstring>
#include <iostream>
using namespace std;
struct Edge {
int v, next;
} edge[200010];
int head[100010], cnt;
int n, dis[100010], start;
void addEdge(int u, int v) {
edge[++cnt].v = v;
edge[cnt].next = head[u];
head[u] = cnt;
}
void dfs(int x, int fa) {
for (int i = head[x]; i; i = edge[i].next) {
int v = edge[i].v;
if (v != fa) {
dis[v] = dis[x] + 1;
dfs(v, x);
}
}
}
int main() {
ios::sync_with_stdio(false);
cin >> n;
for (int i = 1; i < n; ++i) {
int x, y;
cin >> x >> y;
addEdge(x, y);
addEdge(y, x);
}
memset(dis, 0x3f3f3f3f, sizeof(dis));
dis[1] = 0;
dfs(1, 0);
int maxn = -1;
for (int i = 1; i <= n; ++i) {
if (dis[i] > maxn) {
maxn = dis[i];
start = i; // 树的直径的起点
}
}
memset(dis, 0x3f3f3f3f, sizeof(dis));
dis[start] = 0;
dfs(start, 0);
maxn = -1;
for (int i = 1; i <= n; ++i) {
if (dis[i] > maxn) {
maxn = dis[i];
}
}
cout << maxn << endl;
return 0;
}