题目1536:树的最小高度 树的直径(个人经典代码)

题目1536:树的最小高度

时间限制:5 秒

内存限制:128 兆

题目描述:

给定一棵无向树, 我们选择不同的节点作为根节点时,可以得到不同的高度(即树根节点到叶子节点距离的最大值), 现在求这棵树可能的最低高度。

 

输入:

输入可能包含多个测试案例。
对于每个测试案例,输入的第一行为一个整数n(1 <= n <= 1000000)。
接下n-1行,每行包括两个整数u,v( 0<= u,v < n)代表这棵树的一个边连接的两个顶点。

 

输出:

对应每个测试案例,输出这棵树可能的最小高度。

 

样例输入:
3
0 1
1 2
5
0 1
1 2
1 3
1 4
样例输出:
1
1

#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <fstream>
#include <vector>
#define Min(a,b) ((a)<(b)?(a):(b))
#pragma comment(linker, "/STACK:16777216")
using namespace std ;
typedef long long LL ;
const int size=1000008 ;
struct Edge{
    int v ;
    int next ;
};
Edge  edge[size*2] ;
int vec[size] ,dist[size];
int id ,N;
bool visited[size] ;
inline void add_edge(int u ,int v){
    edge[id].v=v ;
    edge[id].next=vec[u] ;
    vec[u]=id++ ;
}
void init(){
    id=0 ;
    fill(vec,vec+N,-1) ;
    fill(dist,dist+N,0) ;
    fill(visited,visited+N,0) ;
}
void dfs(int father,int high){
    visited[father]=1 ;
    dist[father]=high ;
    for(int e=vec[father];e!=-1;e=edge[e].next){
        int son=edge[e].v ;
        if(visited[son])
             continue ;
        dfs(son,high+1) ;
    }
}
int gao(){
    init() ;
    int u ,v ;
    for(int i=1;i<N;i++){
         scanf("%d%d",&u,&v) ;
         add_edge(u,v) ;
         add_edge(v,u) ;
    }
    dfs(0,0) ;
    int start=max_element(dist,dist+N)-dist ;
    //printf("%d\n",start) ;
    fill(dist,dist+N,0) ;
    fill(visited,visited+N,0) ;
    dfs(start,0) ;
    int Height=*max_element(dist,dist+N) ;
    if(Height&1)
        return Height/2 +1 ;
    else
        return Height/2 ;
}
int main(){
   while(scanf("%d",&N)!=EOF){
       printf("%d\n",gao()) ;
   }
   return 0 ;
}
 

 

转载于:https://www.cnblogs.com/liyangtianmen/p/3311234.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值