P3174 [HAOI2009]毛毛虫
\(dp_i\)表示节点i为头的最长毛毛虫
(我这里i的父节点呗算作腿的一条)
然后就可以不用特判地进行转移
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define int long long
using namespace std;
int n,m;
struct ed{
int to;
int ne;
}ed[600005];
int p;
int head[300005];
int dp[300005];
int ans;
void add(int f,int to){
p++;
ed[p].to=to;
ed[p].ne=head[f];
head[f]=p;
}
int x,y;
int num[300005];
void dfs(int r,int f){
dp[r]=num[r]+1;
int mx1=0;
int mx2=0;
for(int i=head[r];i;i=ed[i].ne){
if(ed[i].to==f) continue;
int v=ed[i].to;
dfs(v,r);
dp[r]=max(dp[r],dp[v]+num[r]-1);
if(dp[v]>mx1){
mx2=mx1;
mx1=dp[v];
}else if(dp[v]>mx2)
mx2=dp[v];
}
ans=max(max(ans,dp[r]),mx1+mx2-3+num[r]);
return ;
}
signed main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=m;++i){
scanf("%d%d",&x,&y);
add(x,y);
add(y,x);
num[x]++;
num[y]++;
}
dfs(1,0);
cout<<ans;
return 0;
}