链接:https://www.nowcoder.com/acm/contest/136/C
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 262144K,其他语言524288K
64bit IO Format: %lld
题目描述
桃花一簇开无主,可爱深红映浅红。
——《题百叶桃花》
桃花长在桃树上,树的每个节点有一个桃花,调皮的HtBest想摘尽可能多的桃花。HtBest有一个魔法棒,摘到树上任意一条链上的所有桃花,由于HtBest法力有限,只能使用一次魔法棒,请求出Htbest最多可以摘到多少个桃花。
输入描述:
第一行有一个正整数n,表示桃树的节点个数。
接下来n-1行,第i行两个正整数ai,bi ,表示桃树上的节点ai,bi之间有一条边。
输出描述:
第一行一个整数,表示HtBest使用一次魔法棒最多可以摘到多少桃花。
示例1
输入
复制
3
1 2
2 3
输出
复制
3
示例2
输入
复制
3
1 2
1 3
输出
复制
3
示例3
输入
复制
4
1 2
2 3
3 4
输出
复制
4
备注:
对于100%的测试数据:
1 ≤ n ≤ 1000000
数据量较大,注意使用更快的输入输出方式。
思路:
之前超时代码,每个点都搜索一遍,(妥妥的超时)
后来看了一下别人的代码,可以从第一个点开始搜索,点1的深度为1,记录最大深度,以及其对应的点。
然后从该点搜索,并设深度为1,就可以找到最大的深度。
代码如下:
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
const int INF=0x3f3f3f3f,N=1000003;
int n,s,maxdep=0;
int vis[N],tot=0,head[N];
struct proc{int to,next;};
proc edge[2*N];
void addEdge(int x,int y){
edge[tot].to=y;
edge[tot].next=head[x];
head[x]=tot++;
}
void dfs(int x,int pre,int dep){
vis[x]=1;
if(dep>maxdep){maxdep=dep;s=x;}
for(int i=head[x];i!=-1;i=edge[i].next){
int t=edge[i].to;
if(t!=pre){
dfs(t,x,dep+1);
}
}
return ;
}
int main(){
int a,b;
scanf("%d",&n);
tot=0;
memset(head,-1,sizeof(head));
for(int i=1;i<n;i++){
scanf("%d%d",&a,&b);
addEdge(a,b);
addEdge(b,a);
}
dfs(1,-1,1);
maxdep=0;
dfs(s,-1,1);
printf("%d\n",maxdep);
}