Park Visit
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 122 Accepted Submission(s): 54
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≤10 5), 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≤10 5), 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这是一道图论题,由于生成树不带权值,因此比较适合BFS,但本人习惯DFS,所以用了DFS;本题需要找出最长的那条路径lp,这是题目的关键所在。对于k<=lp,答案为k-1对于k>lp,答案为最长的路径走一次,剩余的走两次,即2*(k-1-lp)+lp#include<iostream> #include<cstdio> #include<cstring> using namespace std; const int MAX=100000+20; typedef struct node1 { int i; node1 *next; }Edg; typedef struct node2 { int tag; Edg *first; }VEC; typedef struct node3 { VEC Vec[MAX]; int num; }Graph; int n,m,deep,ind; void DFS(Graph &G,int i,int tdep) { Edg *p; G.Vec[i].tag=1; p=G.Vec[i].first; if(tdep>deep) { ind=i;//存放最长路径叶节点 deep=tdep;//存放最长路径长度 } while(p!=NULL) { if(G.Vec[p->i].tag==0) { DFS(G,p->i,tdep+1); G.Vec[p->i].tag=0; } p=p->next; } } int main() { int cas,i,a,b,k; cin>>cas; while(cas--) { scanf("%d%d",&n,&m); Graph G; G.num=n; Edg *p; for(i=1;i<=n;i++) G.Vec[i].tag=0,G.Vec[i].first=NULL; //建立无向图+邻接表 for(i=1;i<n;i++) { scanf("%d%d",&a,&b); p=new Edg; p->i=b; p->next=G.Vec[a].first; G.Vec[a].first=p; p=new Edg; p->i=a; p->next=G.Vec[b].first; G.Vec[b].first=p; } deep=-1; DFS(G,p->i,0); deep=-1; for(i=1;i<=n;i++) G.Vec[i].tag=0; DFS(G,ind,0); for(i=0;i<m;i++) { scanf("%d",&k); if(k<=deep) printf("%d\n",k-1); else printf("%d\n",(k-deep-1)*2+deep); } } return 0; }