Test Instructions Description
Ideas
[HAOI2009] Caterpillar
Tree-shaped DP
The largest caterpillar can be seen as the root of a single node
Two chains with the largest number of nodes and directly adjacent nodes in the subtree
The number of points that are directly connected to I in the subtree of I using the Con[now] array
(Con[now in the code] includes now itself)
Assuming the root now=6, the yellow part
Use Num[now] to indicate the maximum number of links and directly connected points of a subtree with now roots
Assuming the root now=6, the red part
Note "The chain of points and the most directly adjacent to the link" in this abbreviation "longest Chain"
Num transfer can be written: Num[now]=max (num[now],num[v]+con[now]-1)
We end up asking for two chains, which is equivalent to the longest chain and the
There is no need to cycle once to find the second chain.
You can directly set the global variable answer to record the maximum value of the longest chain in the +i subtree before the num[i update
Updated: Answer=max (answer,num[u]+num[v]-1)
1 is due to V-point repetition
Note, however, that if the root node of both chains in the answer is not 1,
So this caterpillar also includes the Father node of the root node
If the root node happens to be 1, there is no so-called "Father Node"
So we have to judge.
Set Select[i]=true to indicate that the root node is I
The final judgment can be
#include <iostream>#include<cstring>#include<cstdio>#defineN 300005using namespacestd;intn,m;structedge{intU,V,NXT;} E[n*2];intCnt,first[n];voidAdd_edge (intXinty) {e[++cnt].u=x; E[CNT].V=y; E[CNT].NXT=First[x]; FIRST[X]=CNT;}BOOLVis[n];intNum[n],con[n];voidDfsintNowintfat) {Vis[now]=true; for(intI=first[now];i;i=e[i].nxt) { intv=e[i].v; if(!Vis[v]) {DFS (V,now); Con[now]++; } }}intanswer;BOOL Select[N];voiddpintNow ) {Num[now]=Con[now]; Vis[now]=true; for(intI=first[now];i;i=e[i].nxt) { intv=e[i].v; if(!Vis[v]) {DP (v); if(answer<num[now]+num[v]-1) {Answer=num[now]+num[v]-1; Select[now]=true; }//Answer=max (answer,num[u]+num[v]-1);Num[now]=max (num[now],num[v]+con[now]-1); } }}intMain () {scanf ("%d%d",&n,&m); for(intI=1; i<=n;i++) con[i]=1; for(intI=1; i<=m;i++){ intX,Y;SCANF ("%d%d",&x,&y); Add_edge (x, y); Add_edge (Y,X); } DFS (1,0);//for (int i=1;i<=n;i++) {//printf ("%d:%d%d\n", I,con[i],num[i]);// }memset (Vis,false,sizeof(VIS)); DP (1); if(!Select[1]) answer++; printf ("%d\n", answer); return 0;}
[HAOI2009] Caterpillar