Question Description
For a tree, we can pull a chain and the edge connected to the chain, it looks like a caterpillar, the more points, the bigger the caterpillar. For example, the tree on the left (Figure 1) pulls part of it into a caterpillar on the right (Figure 2).
Input data
In the text file worm.in, the first row of two integers N, M, respectively, represents the number of nodes in the tree and the number of sides of the tree.
Next M lines, two integers a per line, b for Point A and point B have edge connections (a, b≤n). You can assume that no pair of the same (a, b) will appear more than once.
Output data
Writes an integer in the text file worm.out that represents the size of the largest caterpillar.
Sample input
13 12
1 2
1 5
1 6
3 2
4 2
5 7
5 8
7 9
7 10
7 11
8 12
8 13
Sample output
11
Test data range
40% of data, n≤50000
100% of data, n≤300000
Exercises
It would be nice to have a deep search. Note that parent nodes are sometimes counted as well.
#include <iostream>#include <cstdio>#include <cstring>using namespace STD;structuse{intSt,en;} b[1000001];intf[1000001],n,m,a,bb,cnt,ans,son[1000001],next[1000001],point[1000001];inline voidAddintXintY) {next[++cnt]=point[x];p oint[x]=cnt; B[cnt].st=x;b[cnt].en=y;}inline voiddpintXintFA) {intMaxx (-100000), temp; F[X]=SON[X]; for(intI=point[x];i;i=next[i])if(B[I].EN!=FA) {DP (B[I].EN,X); Ans=max (ans,maxx+f[b[i].en]+1+son[x]-2); Maxx=max (Maxx,f[b[i].en]); f[x]=maxx+son[x]-1; }}intMain () {Freopen ("Worma.in","R", stdin); Freopen ("Worma.out","W", stdout);scanf("%d%d", &n,&m); for(intI=1; i<=m;i++) {scanf("%d%d", &A,&BB); Add (A,BB); add (bb,a); son[a]++;son[bb]++; } DP (1,0);cout<<ans;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"HAOI2009" "Caterpillar" "tree-shaped DP"