题意翻译
题目描述 给你一个无权无向的树。编写程序以输出该树中最长路径(从一个节点到另一个节点)的长度。在这种情况下,路径的长度是我们从开始到目的地的遍历边数。
输入输出格式
输入格式: 输入文件的第一行包含一个整数N —树中的节点数(0 < N <= 10000)。接下来N -1行包含该树的N -1个边—每行包含一对(u,v),表示在节点u和节点v之间存在边(1 <= u,v <= N)。
输出格式: 一行:输出最长路径的长度。
题目描述
You are given an unweighted, undirected tree. Write a program to output the length of the longest path (from one node to another) in that tree. The length of a path in this case is number of edges we traverse from source to destination.
输入输出格式
输入格式:
The first line of the input file contains one integer N — number of nodes in the tree (0 < N <= 10000). Next N-1 lines contain N-1 edges of that tree — Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u, v <= N).
输出格式:
Print the length of the longest path on one line.
输入输出样例
输入样例#1: 复制
3
1 2
2 3
输出样例#1: 复制
2
思路:树的直径,求u到叶节点的最大值f1与次大值f2,ans=max{f1+f2}
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=20005;
int n,ans;
int tot,head[N],adj[N],nxt[N];
int f1[N],f2[N];
void add(int u,int v)
{
tot++;
nxt[tot]=head[u];
head[u]=tot;
adj[tot]=v;
}
int mx(int x,int y)
{
return x>y?x:y;
}
void dfs(int u,int fa)
{
int i;
for(i=head[u];i;i=nxt[i])
{
int v=adj[i];
if(v==fa)continue;
dfs(v,u);
if(f1[u]<f1[v]+1)
{
f2[u]=f1[u];
f1[u]=f1[v]+1;
}
else if(f2[u]<f1[v]+1)
f2[u]=f1[v]+1;
ans=mx(ans,f1[u]+f2[u]);
}
}
int main()
{
//freopen("path.in","r",stdin);
//freopen("path.out","w",stdout);
int i,x,y;
scanf("%d",&n);
for(i=1;i<n;i++)
{
scanf("%d%d",&x,&y);
add(x,y);
add(y,x);
}
dfs(1,0);
printf("%d\n",ans);
return 0;
}