多校联合赛(一) 1008 Park Visit

来源:互联网 发布:止汗露的危害 知乎 编辑:程序博客网 时间:2024/06/06 06:56
题目是这样的
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
即找出一个入口走完需要的旅游点要求最短路。
怎么想呢?
我们肯定要好好利用这个图中最长的那条路,如果需要的旅游点数少于最长路上的点,那就每个只用走一次。如果超了,就在分支上走,每个走两次即可。
#include<queue>#include<cstring>#include<cstdio>#include<iostream>using namespace std;#define MAXV 200010#define MAXE 200010typedef struct{    int t,w,next;}Edge;Edge edge[MAXE];int n,m;int e,head[MAXV] ,record[MAXV];void addedge(int s,int t,int w){    edge[e].t=t;    edge[e].w=w;    edge[e].next=head[s];    head[s]=e++;}int bfs(int s,int flag){    int i,v,t;    int tmp=0,tmpi=s;    queue <int>q;    memset(record,-1,sizeof(record));    record[s]=0;    q.push(s);    while(!q.empty()){        v=q.front();q.pop();        for(i=head[v];i!=-1;i=edge[i].next){            t=edge[i].t;            if(record[t]==-1){                record[t]=record[v]+edge[i].w;                if(record[t]>tmp){                    tmp=record[t];                    tmpi=t;                }                q.push(t);            }        }    }    return flag?tmpi:tmp;}int main(){    int a,b,w,ans,t,part;scanf("%d",&t);while(t--){scanf("%d%d\n",&n,&m);memset(head,-1,sizeof(head));e=0;for(int i = 0;i<n-1;i++){scanf("%d %d",&a,&b);addedge(a,b,1);addedge(b,a,1);}a = bfs(1,1);ans = bfs(a,0);          //求最长路,来回两次bfs的算法for(int i = 0;i<m;i++){scanf("%d",&part);if(part<=ans+1){printf("%d\n",part-1);}else{printf("%d\n",2*part-ans-2);}}}    return 0;}