牛客网小白月赛6C(DFS,思维)

#include<bits/stdc++.h>
using namespace std;
vector<int>tree[1000010];
int sum=0;
int dfs(int x, int y)
{
    int first = 0, second = 0;
    for (int i = 0; i < tree[y].size(); ++i)
    {
        if (tree[y][i] == x)
            continue;
        int temp = dfs(y, tree[y][i]);
        if (temp>first)
        {
            second = first;
            first = temp;
        }
        else if (temp > second)
        {
            second = temp;
        }
    }
    sum=max(sum,first+second);
    return first+1;
}
int main()
{
    int n;
    scanf("%d",&n);
    int a,b;
    for(int i=1;i<=n;i++)
    {
        scanf("%d%d",&a,&b);
        tree[a].push_back(b);
        tree[b].push_back(a);
    }
    dfs(0,1);
    printf("%d",sum+1);
    return 0;
}

posted @ 2018-08-20 09:57  sewage  阅读(140)  评论(0编辑  收藏  举报