题解报告:hdu 4607 Park Visit(最长路+规律)
Posted acgoto
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了题解报告:hdu 4607 Park Visit(最长路+规律)相关的知识,希望对你有一定的参考价值。
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?
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.
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 ",k-1); 40 else printf("%d ",maxdist+(k-maxdist-1)*2); 41 } 42 } 43 } 44 return 0; 45 }
以上是关于题解报告:hdu 4607 Park Visit(最长路+规律)的主要内容,如果未能解决你的问题,请参考以下文章