PT07Z - Longest path in a tree【洛谷SP1437】

题意翻译

题目描述 给你一个无权无向的树。编写程序以输出该树中最长路径(从一个节点到另一个节点)的长度。在这种情况下,路径的长度是我们从开始到目的地的遍历边数。

输入输出格式

输入格式: 输入文件的第一行包含一个整数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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值