树上最长链

https://www.luogu.com.cn/problem/U182917

#include <bits/stdc++.h>
using namespace std;

const int N = 3000010;

bool vis[N];
int to[N];
int nxt[N];
int head[N];
int E;

void init()
{
	E = 0;
	memset(head, -1, sizeof head);
}

void add_edge(int a, int b)
{
	to[E] = b;
	nxt[E] = head[a];
	head[a] = E ++;
}

int dep[N];

int dfs(int u)
{
	vis[u] = true;
	if (dep[u] != 0)
		return dep[u];
	int ans = 1;
	for (int i = head[u]; ~i; i = nxt[i])
	{
		int v = to[i];
		if (vis[v])
			continue ;
		ans = max(ans, dfs(v) + 1);
	}
	return dep[u] = ans;
}

int main()
{
	int n;
	cin >> n;
	init();
	if (n == 0)
	{
		puts("0");
		return 0;
	}
	for (int i = 1; i < n; i ++)
	{
		int a, b;
		scanf ("%d%d", &a, &b);
		add_edge(a, b);
		add_edge(b, a);
	}
	for (int i = 1; i <= n; i ++)
		dfs(i);
	int mx = 1;
	for (int i = 1; i <= n; i ++)
		mx = max(mx, dep[i]);
	cout << mx << endl;
	return 0;
}	


上一篇:数据结构实验一:7-1 两个有序链表序列的合并


下一篇:DFS(深度优先搜索)模板