hihocoder 1050树中最长路

枚举每一个点作为转折点t,求出以t为根节点的子树中的‘最长路’以及与‘最长路’不重合的‘次长路’,用这两条路的长度之和去更新答案,那么最终的答案就是这棵树的最长路长度了
用first(t),second(t)分别表示以t为根节点的子树中最长路和次长路的长度,那么我只需要求出t的所有子结点的first值,first(t)便是这些first值中的最大值+1,second(t)便是这些first值中的次大值+1
以类似后序遍历的方式依次访问每个结点,从下往上依次计算每个结点的first值和second值,我就能够用O(N)的时间复杂度来解决这个问题

/**/
#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
", ans);

	return 0;
}
/*
    input:
    output:
    modeling:
    methods:
    complexity:
    summary:
*/
原文地址:https://www.cnblogs.com/000what/p/11651962.html