The details of this problem are handled quite a lot, but AC is not difficult;
The maximum length of the caterpillar is f[i], then F[i]=max (F[j]) +i The child number of the node, which can be formed by a subtree of the root node;
The answer requires the merging of two sub-trees of F Max and ans++, and if the merging position is not the root node;
I was the pit at the last point, and finally hit the table to find the problem;
1#include <iostream>2#include <cstdio>3#include <cstring>4 using namespacestd;5 Const intmaxn=303000;6 intN,M,F[MAXN],CHILD[MAXN];7 structnode{8 intY,next;9}e[maxn<<1];Ten intlinkk[maxn],len=0; One voidInsertintXinty) { Ae[++len].y=y; -e[len].next=Linkk[x]; -linkk[x]=Len; the } - voidinit () { -scanf"%d%d",&n,&m); - intx, y; + for(intI=1; i<=m;i++){ -scanf"%d%d",&x,&y); + Insert (x, y); insert (y,x); A } at } - voidDfsintXintFA) { - for(intI=linkk[x];i;i=E[i].next) { - if(E[I].Y==FA)Continue; -child[x]++; - DFS (e[i].y,x); in } - } to intans=0; + voidDfs (intXintFA) { - if(child[x]==0){ thef[x]=1;return; * } $ intmaxx[2]={0,0};Panax Notoginseng for(intI=linkk[x];i;i=E[i].next) { - if(E[I].Y==FA)Continue; the Dfs (e[i].y,x); +F[x]=max (f[x],f[e[i].y]+child[x]); A if(f[e[i].y]>maxx[0]) maxx[0]=F[E[I].Y]; the if(f[e[i].y]>maxx[1]) maxx[0]=maxx[1],maxx[1]=F[E[I].Y]; + } -Ans=max (ans,f[x]+maxx[0]-1); $ if(x!=1) Ans=max (ans,f[x]+maxx[0]); $ if(maxx[0]==0) ans=Max (ans,f[x]); - } - voidWork () { theDfs1,0); -Dfs (1,0);Wuyiprintf"%d\n", ans); the } - intMain () { WuFreopen ("1.in","R", stdin); -Freopen ("1.out","W", stdout); About init (); $ Work (); -}
View Code
[haoi2009] Caterpillar tree-shaped DP