1912: [Apio2010]patrol patrol time limit:4 Sec Memory limit:64 MB
submit:1034 solved:562
[Submit] [Status] [Discuss] The first line of Descriptioninput contains two integers n, K (1≤k≤2). Next n–1 line, two integers a, b per line, indicates that there is a road between village A and B (1≤a, b≤n). Output outputs an integer that represents the minimum patrol distance that can be reached after a new K-road is created. Sample Input8 1
1 2
3 1
3 4
5 3
9 {
8 5
5 6Sample Output OneHINT
10% of the data, n≤1000, K = 1;
30% of the data, K = 1;
80% of the data, the number of villages adjacent to each village does not exceed 25;
90% of the data, the number of villages adjacent to each village does not exceed 150;
100% of the data, 3≤n≤100,000, 1≤k≤2.
SourceSolution
It is found that the edge is actually formed ring, so that a path can be directly around the back without the original path back
So when the k==1, the edge must be used to even the longest path (the diameter of the tree) so DFS out can
K==2 the same time, but it takes a short time, the same DFS, the first DFS evaluated the path to make some changes, set to 1 can be
Code
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>using namespacestd;intRead () {intx=0, f=1;CharCh=GetChar (); while(ch<'0'|| Ch>'9'){if(ch=='-') f=-1; ch=GetChar ();} while(ch>='0'&&ch<='9') {x=x*Ten+ch-'0'; ch=GetChar ();} returnx*F;}#defineMAXN 100010intn,k,ans,zj,s;structedgenode{intNext,to,len;} edge[maxn<<1];intHead[maxn],cnt=1;introad[maxn]={0},croad[maxn]={0};voidAddintUintVintW) {CNT++; Edge[cnt].to=v; Edge[cnt].next=head[u]; head[u]=cnt; edge[cnt].len=W;}voidInsertintUintVintW) {Add (u,v,w); add (v,u,w);}intDFS (intNowintFA) { intMaxd=0, cmaxd=0; for(intI=head[now]; I I=edge[i].next)if(edge[i].to!=FA) { intLen=dfs (Edge[i].to,now) +Edge[i].len; if(Len>maxd) cmaxd=maxd,maxd=len,croad[now]=road[now],road[now]=i; Else if(Len>cmaxd) cmaxd=len,croad[now]=i; } if(MAXD+CMAXD>ZJ) zj=maxd+cmaxd,s=Now ;//printf ("%d%d%d%d\n", now,fa,maxd,cmaxd); returnMaxd;}intMain () {n=read (); k=read (); for(intU,v,i=1; i<=n-1; i++) U=read (), V=read (), insert (U,v,1); DFS (1,0); ans=2* (n1)-zj+1; if(k==2) { for(intI=road[s]; I I=road[edge[i].to]) edge[i].len=edge[i^1].len=-1; for(intI=croad[s]; I I=road[edge[i].to]) edge[i].len=edge[i^1].len=-1; ZJ=0; DFS (1,0); ans=ans-zj+1; } printf ("%d\n", ans); return 0;}
own code to write fried, do not know why.
"BZOJ-1912" patrol patrol tree diameter + DFS (tree dp)