HDOJ-----4607

来源:互联网 发布:校园网mac地址修改 编辑:程序博客网 时间:2024/05/02 01:28

Park Visit

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3271    Accepted Submission(s): 1463


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
14 23 21 24 224
 

Sample Output
14

就是给出点的关系,问走过n需要最少走几条边,一次回头路算一条边,所以n不大于最长路就是n-1,大于的话,根据神奇的数学定理就是,最长路有k条边,结果就是k-1+(n-k)*2


#include<cstdio>#include<cstring>#include<queue>#include<algorithm>#define maxn 100010 using namespace std;int ans, num, ok, nod, cnt;int dis[maxn], head[maxn];bool vis[maxn];struct node{int from, to, val, next;}edge[maxn*2];void add(int u, int v, int w){edge[num].from = u;edge[num].to = v;edge[num].val = w;edge[num].next = head[u];head[u] = num++;}void bfs(int t){memset(vis, false, sizeof(vis));memset(dis, 0, sizeof(dis));queue<int > Q;Q.push(t);vis[t] = true;ans = 0;while(!Q.empty()){int u = Q.front();Q.pop();for(int i = head[u]; i != -1; i = edge[i].next){int v = edge[i].to;if(!vis[v]){dis[v] = edge[i].val + dis[u];vis[v] = true;Q.push(v);if(ans < dis[v]){ans = dis[v];nod = v;}}}}}int main(){int m, n, a, b, c, t;scanf("%d", &t);while(t--){scanf("%d%d", &m, &n);memset(head, -1, sizeof(head));num = ok = 0;for(int i = 0; i < m-1; i++){scanf("%d%d", &a, &b);add(a, b, 1);add(b, a, 1);}bfs(1);bfs(nod);for(int i = 0; i < n; i++){scanf("%d", &c);if(c-1 <= ans){printf("%d\n", c-1);}else{printf("%d\n", ans + (c-(ans+1))*2);}}}return 0;}


0 0