#树的直径#洛谷 3174 [HAOI2009]毛毛虫
分析
类似于树的直径,只是点权变成了出度-1,
注意减1之后会漏掉两个端点要加回去,当\(n=1\)时特判
代码
#include <cstdio>
#include <cctype>
#define rr register
using namespace std;
const int N=300011;
struct node{int y,next;}e[N<<1];
int deg[N],ls[N],n,k,mx,rt;
inline signed iut(){
rr int ans=0; rr char c=getchar();
while (!isdigit(c)) c=getchar();
while (isdigit(c)) ans=(ans<<3)+(ans<<1)+(c^48),c=getchar();
return ans;
}
inline void dfs(int x,int fa,int sum){
if (mx<sum) mx=sum,rt=x;
for (rr int i=ls[x];i;i=e[i].next)
if (e[i].y!=fa) dfs(e[i].y,x,sum+deg[e[i].y]);
}
signed main(){
n=iut(),iut(),k=1;
if (n==1) return !putchar(49);
for (rr int i=1;i<=n;++i) deg[i]=-1;
for (rr int i=1;i<n;++i){
rr int x=iut(),y=iut();
e[++k]=(node){y,ls[x]},ls[x]=k,++deg[x],
e[++k]=(node){x,ls[y]},ls[y]=k,++deg[y];
}
dfs(1,0,deg[1]),mx=0,dfs(rt,0,deg[rt]);
return !printf("%d",mx+2);
}