牛客小白月赛6 C 题 桃花

题目链接:https://www.nowcoder.com/acm/contest/136/C

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int maxDistance = 0;
vector<vector<int> > G(1000001);
inline void AddEdge(int v, int s){
    G[v].push_back(s);
    G[s].push_back(v);
}
int LastOrder(int pre, int cur){
    int first = 0, second = 0;
    for (size_t i = 0; i < G[cur].size(); ++i){
        if (G[cur][i] == pre)
            continue;
        int temp = LastOrder(cur, G[cur][i]);
        if (temp>first){
            second = first;
            first = temp;
        }else if (temp > second){
            second = temp;
        }
  
    }
    maxDistance = maxDistance>first+second?maxDistance:first+second;
    return first + 1;
}
int Scan() {   
    int res = 0, flag = 0; 
    char ch; 
    if ((ch = getchar()) == '-') {  
        flag = 1; 
    }else if(ch >= '0' && ch <= '9') {
        res = ch - '0';
    }
    while ((ch = getchar()) >= '0' && ch <= '9'){
        res = res * 10 + (ch - '0'); 
    }
    return flag ? -res : res; 
} 
int main(){
    int n;
    scanf("%d", &n);
    int x, y;
    for (int i = 1; i < n; ++i) {
        x = Scan();
        y = Scan();
        AddEdge(x, y);
    }
    LastOrder(0, 1);
    printf("%d\n", maxDistance+1);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Adusts/article/details/81813827
今日推荐