题目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
",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
",gao()) ;
   }
   return 0 ;
}
 
原文地址:https://www.cnblogs.com/liyangtianmen/p/3311234.html