hihocoder 1050 tree longest road

Each point as a turning point in the enumeration t, t is determined in the subtree root node in the 'longest path' and a 'channel up' does not overlap 'times long road', the length of these two directions of and to update the answer, then the final answer is the tree of the longest path length
with a first (t), second (t ) represent the length t is the root of the subtree longest road and the chief of the road, so if you ask me the first child node of the value of all the t's, first (t) is the first value of the maximum value + 1, second (t) is the second largest value of these first values of +1
in a similar postorder fashion sequentially access each node, up sequentially calculated first value and second value from each node, I can use the time complexity of O (N) to solve the problem

/**/
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <stack>
#include <queue>

typedef long long LL;
typedef unsigned long long ULL;
using namespace std;

bool Sqrt(LL n) { return (LL)sqrt(n) * sqrt(n) == n; }
const double PI = acos(-1.0), ESP = 1e-10;
const LL INF = 99999999999999;
const int inf = 999999999, N = 1e5 + 24;
int n, a, b, ans, First[N], Second[N];
vector<int> E[N];
bool vis[N];

void dfs(int u)
{
    vis[u] = 1; First[u] = 0; Second[u] = 0; //不要忘记状态修改和初始化
    for(auto v : E[u]) {
        if(!vis[v]) {
            dfs(v);
            if(First[v] + 1 >= First[u]) {
                Second[u] = First[u];
                First[u] = First[v] + 1;
            }
            else if(First[v] + 1 > Second[u]) {
                Second[u] = First[v] + 1;
            }
        }
    }
    ans = max(ans, First[u] + Second[u]); //不要忘记更新ans
}

int main()
{
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    scanf("%d", &n);
    memset(First, -1, sizeof First);
    memset(Second, -1, sizeof Second);
    memset(vis, 0, sizeof vis);
    for(int i = 1; i < n; i++) {
        scanf("%d%d", &a, &b);
        E[a].push_back(b); E[b].push_back(a);
    }
    dfs(1);
    printf("%d\n", ans);

    return 0;
}
/*
    input:
    output:
    modeling:
    methods:
    complexity:
    summary:
*/

Guess you like

Origin www.cnblogs.com/000what/p/11651962.html