1. 程式人生 > >題解報告:hdu 4607 Park Visit(最長路+規律)

題解報告:hdu 4607 Park Visit(最長路+規律)

inpu follow nodes 一點 dfs ems ios eno sca

Problem Description

Claire and her little friend, ykwd, are travelling in Shevchenko‘s Park! The park is beautiful - but large, indeed. N feature spots in the park are connected by exactly (N-1) undirected paths, and Claire is too tired to visit all of them. After consideration, she decides to visit only K spots among them. She takes out a map of the park, and luckily, finds that there‘re entrances at each feature spot! Claire wants to choose an entrance, and find a way of visit to minimize the distance she has to walk. For convenience, we can assume the length of all paths are 1.
Claire is too tired. Can you help her?

Input

An integer T(T≤20) will exist in the first line of input, indicating the number of test cases.
Each test case begins with two integers N and M(1≤N,M≤105), which respectively denotes the number of nodes and queries.
The following (N-1) lines, each with a pair of integers (u,v), describe the tree edges.
The following M lines, each with an integer K(1≤K≤N), describe the queries.
The nodes are labeled from 1 to N.

Output

For each query, output the minimum walking distance, one per line.

Sample Input

1 4 2 3 2 1 2 4 2 2 4

Sample Output

1 4 解題思路:看到這題肯定會想到用樹的直徑來求解,題目要求從某一點出發,訪問連續k個點走過的最少邊數。顯然這個時候如果k個點都在樹的直徑上,那麽經過的邊數一定是最少的且為k-1,否則(即k>maxdist)就會經過樹直徑外的一些點,每個點被訪問兩次,因此此時經過的邊數最少為maxdist+(k-maxdist-1)*2。 AC代碼(499ms):
 1 #include<iostream>
 2 #include<string.h>
 3 #include<cstdio>
 4 using namespace std;
 5 const int maxn=1e5+5;
 6 struct EDGE{int to,next;}edge[maxn<<1];
 7 int t,n,m,k,x,y,cnt,res,maxdist,head[maxn];
 8 void add_edge(int u,int v){
 9     edge[cnt].to=v;
10     edge[cnt].next=head[u];
11     head[u]=cnt++;
12 }
13 int dfs(int u,int fa,int &maxdist){
14     int Dmax=0,Dsec=0;
15     for(int i=head[u];~i;i=edge[i].next){
16         int v=edge[i].to;
17         if(v^fa){
18             int nowd=dfs(v,u,maxdist)+1;
19             if(nowd>Dmax)Dsec=Dmax,Dmax=nowd;
20             else if(nowd>Dsec)Dsec=nowd;
21         }
22     }
23     maxdist=max(maxdist,Dmax+Dsec);
24     return Dmax;
25 }
26 int main(){
27     while(~scanf("%d",&t)){
28         while(t--){
29             scanf("%d%d",&n,&m);
30             memset(head,-1,sizeof(head));cnt=maxdist=0;
31             while(--n){
32                 scanf("%d%d",&x,&y);
33                 add_edge(x,y);
34                 add_edge(y,x);
35             }
36             dfs(1,-1,maxdist);
37             while(m--){
38                 scanf("%d",&k);
39                 if(k<=maxdist)printf("%d\n",k-1);
40                 else printf("%d\n",maxdist+(k-maxdist-1)*2);
41             }
42         }
43     }
44     return 0;
45 }

題解報告:hdu 4607 Park Visit(最長路+規律)