题目描述 https://loj.ac/problem/10159
首先是求树中最长链的问题,只需遍历一遍,更新每个点距离的最大值和次大值,枚举一遍,记下答案ans。
如果此时暴搜的话,找出路径为ans的边上的点,是可以得出答案的,但会超时。我们可以根据记下的最大值以及次大值来找路径,找出相加为ans的点,搜索,如果搜到的子节点最大值为父节点最大值-1,那么这个子节点就在最长的路径上。
50分
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=2e5+5;
int h[N],to[2*N],next[2*N],tot;
int d1[N],d2[N],an[N],st[N],ans,m;
bool fl[N];
void add(int x,int y)
{
to[++tot]=y;
next[tot]=h[x];
h[x]=tot;
}
void dp(int x,int fa)
{
for(int i=h[x];i;i=next[i])
{
int y=to[i];
if(y==fa) continue;
dp(y,x);
if(d1[y]+1>d1[x])
d2[x]=d1[x],d1[x]=d1[y]+1;
else if(d1[y]+1>d2[x])
d2[x]=d1[y]+1;
}
}
void dfs(int x,int fa,int step)