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
Source
#include <cstring> #include <cstdio> #include <vector> #include <queue> using namespace std; #define N 100005 int n,m; vector<int> map[N]; bool vis[N]; /*先求树的直径方法:两遍bfs,任选一点a,求到a点最远的一点b,然后求到b点最远点c 这样b和c之间的路径为树的直径*/ int d; struct node { int pos; int dis; } start,end; node bfs(node k) { memset(vis,0,sizeof(bool)*(n+5)); queue<node> Q; Q.push(k); vis[k.pos]=1; node point,tmp; while(!Q.empty()) { point=Q.front(); Q.pop(); for(int i=0; i<map[point.pos].size(); i++) { if(vis[map[point.pos][i]]) continue; tmp=point; tmp.pos=map[point.pos][i]; tmp.dis=point.dis+1; vis[tmp.pos]=1; Q.push(tmp); } } d=point.dis; return point; } int main() { int T,a,b; scanf("%d",&T); node k; int q; while(T--) { scanf("%d%d",&n,&m); for(int i=1; i<=n; i++) map[i].clear(); for(int i=1; i<n; i++) { scanf("%d%d",&a,&b); map[a].push_back(b); map[b].push_back(a); } k.pos=1,k.dis=0; start=bfs(k); start.dis=0; end=bfs(start); for(int i=1; i<=m; i++) { scanf("%d",&q); if(q<=d+1) printf("%d\n",q-1); else printf("%d\n",d+(q-d-1)*2); } } return 0; }

浙公网安备 33010602011771号