HDU

来源:互联网 发布:mac excel 数据分析 编辑:程序博客网 时间:2024/06/08 12:10
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≤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
14 23 21 24 224
Sample Output
1

4

思路:

求所给图中的最长连,思路就是以任意的点为起点dfs找到离他最远的点,再以这个最短的点为起点找到的离他最远的点就是要找的点,在找的过程记录查找路径就可以了

如果所给的景点数小于最长路径,直接输出所给景点-1,否则输出最长路径-1+(所给景点-最长路径)*2

ac代码:

#include <iostream>#include <cstdio>#include <cstring>#include <vector>#include <queue>const int maxn=1e5+5;using namespace std;vector<int> mp[maxn];bool vis[maxn];int phi[maxn];int dfs(int t){  memset(vis,0,sizeof(vis));  memset(phi,0,sizeof(phi));  vis[t]=true;  queue<int> p;  int q;  p.push(t);  phi[t]=1;  while(!p.empty())  {     q=p.front();     p.pop();     for(int i=0;i<mp[q].size();i++)     {        if(!vis[mp[q][i]])        {           p.push(mp[q][i]);           vis[mp[q][i]]=true;           phi[mp[q][i]]=phi[q]+1;        }     }  }  return q;}int main(){    int n,a,b,x,y,z;    cin>>n;    while(n--)    {        memset(mp,0,sizeof(mp));        scanf("%d%d",&a,&b);        for(int i=1;i<a;i++)        {            scanf("%d%d",&x,&y);            mp[x].push_back(y);            mp[y].push_back(x);        }        int g=dfs(1);        int h=dfs(g);        int s=phi[h];        for(int i=0;i<b;i++)        {            scanf("%d",&z);            if(z<=s)            printf("%d\n",z-1);            else            printf("%d\n",s-1+(z-s)*2);        }    }    return 0;}

0 0