hihocoder14(2)赛车

题意:本题问你在加一条边的情况下,最长路径是多长。

想法:DFS,搜索出最长,次长路,然后二者求和再减去公共祖先到1点的距离,求出这个最大值

#include<iostream>

#include<cstdio>
#include<string.h>
#include<cstring>
#include<string>
#include<stack>
#include<set>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>

#define LOCAL
#define ll long long
#define lll unsigned long long
#define MAX 1000009
#define eps 1e-8
#define INF 0x7fffffff
#define mod 1000000007

using namespace std;
/*

题意:

想法:

*/
const int MAXN = 100009;
vector<int>g[MAXN];
int ans;

int dfs(int x,int depth)
{
    int frist_depth = 0;
    int second_depth = 0;
    if(g[x].size()==0)
    {
        return depth;
    }
    for(int i = 0;i<g[x].size();i++)
    {
        int v = g[x][i];
        int child_depth = dfs(v,depth + 1);
        cout<<"Father: "<<x<<" Depth "<<depth<<" Son "<<v<<" Longest Depth "<<child_depth<<endl;
        if(child_depth > frist_depth)
        {
            second_depth = frist_depth;
            frist_depth =  child_depth;
        }
        else if(child_depth > second_depth)
        {
            second_depth = child_depth;
        }
    }
    ans = max(ans,frist_depth + second_depth - depth);
    return frist_depth;
}
int main()
{
    //freopen("date.in","r",stdin);
    int n;
    int u,v;
    scanf("%d",&n);
    for(int i = 0;i<n - 1 ;i++){
        scanf("%d%d",&u,&v);
        g[u].push_back(v);
    }
    ans = 0;
    dfs(1,0);
    printf("%d\n",ans);
    return 0;
}

你可能感兴趣的:(hihocoder14(2)赛车)