This problem has been discussed for a long time, has been trying to understand, if according to a traditional random point to find the longest chain, and then back, k=2 when the 1 can not be used to find the longest chain, so, the more strong find the longest chain of the way to come. Something similar to DP. First on the code:
1 Constmaxn=100002;2 type3Node=Record4 F,t,l:longint;5 end;6 varN,k,i,j,ans,num,f,t,diameter,s,sum:longint;7b:array[0..2*MAXN] of node;8head,go1,go2:array[0.. MAXN] of Longint;9Procedure Swap (vara,b:longint);Ten varTem:longint; One begin ATem:=a; A:=b; b:=tem; - end; - procedure Insert (num,f,t:longint); the begin -b[num].f:=Head[f]; -b[num].t:=T; -b[num].l:=1; +head[f]:=num; - end; + function Dfs (x,f:longint): Longint; A varNowe,max1,max2,tem:longint; at begin -max1:=0; max2:=0;//tem:=0; -nowe:=Head[x]; - whileNowe<>0 Do - begin - ifb[nowe].t=F Then in begin -nowe:=b[nowe].f; to Continue; + end; -Tem:=dfs (b[nowe].t,x) +B[NOWE].L; the ifTem>Max1 THEN BEGIN *go2[x]:=Go1[x]; $go1[x]:=Nowe;Panax Notoginsengmax2:=max1; -max1:=tem; the End + Else ifTem>Max2 Then A begin thego2[x]:=Nowe; +max2:=tem; - end; $nowe:=b[nowe].f; $ end; - ifdiameter<max1+Max2 Then - begin thediameter:=max1+Max2; -s:=x;Wuyi end; the exit (MAX1); - end; Wu begin - readln (n,k); About fori:=1to n1 Do $ begin - readln (f,t); -Insert (i*2-1, f,t); -Insert (i*2, t,f); A end; +ans:=2* (n1); thediameter:=0; -Sum:=dfs (1,0); $ans:=ans-diameter+1; the ifK>1 Then the begin thediameter:=0; thei:=Go1[s]; - whileI<>0 Do in begin theb[i].l:=-1; thei:=go1[b[i].t]; About end; thei:=Go2[s]; the whileI<>0 Do the begin +b[i].l:=-1; -i:=go1[b[i].t]; the end;BayiT:=dfs (1,0); theans:=ans-diameter+1; the end; - writeln (ans); -End.
View Code
1 intDiameter,s;//The diameter of the tree is diameter, and the beginning of the diameter is S2 intSON1[MAXV],SON2[MAXV];//record the path of the longest and the second road3 4 intDFS (intUintFA)5 {6 intmax1=0, max2=0;//The longest link to the current point and the road of and the longest chain of FA, or//plus the edge weights associated with FA, as a possible max1 or max2 to connect FA7 for(intP=head[u];p!=-1;p =edges[p].next)8 {9 intv=edges[p].v;Ten if(V==FA)Continue;//keep going down until the leaf node One intNowh=dfs (V,u) +EDGES[P].W; A if(NOWH>MAX1) max2=max1,son2[u]=son1[u],max1=nowh,son1[u]=p; - Else if(NOWH>MAX2) max2=nowh,son2[u]=p; - } the if(DIAMETER<MAX1+MAX2) diameter=max1+max2,s=u; - returnmax1; -}
View Code
And the complexity is O (n).
(Reproduced Please specify Source: http://www.cnblogs.com/Kalenda/)
P1912: [Apio2010]patrol Patrol