hdu 4607 Park Visit(樹的直徑)

Park Visit

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


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
1 4 2 3 2 1 2 4 2 2 4
 

Sample Output
1 4
 


題意:給定一棵樹,從樹中的任意選一個頂點出發,遍歷K個點的最短距
離是多少?(每條邊的長度爲1)

解析:求出樹的最長鏈,若最長鏈的長度爲len,如果K<=len+1,那麼
答案就是K-1,否則就是(K-len-1)*2+len(這個可以自己面圖想想)。


#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
using namespace std;
const int maxn=100010;

int n,m,a[maxn];
vector <int> G[maxn];

void initial()
{
    for(int i=0;i<maxn;i++)  G[i].clear();
    memset(a,0,sizeof(a));
}

void input()
{
    int u,v;
    scanf("%d %d",&n,&m);
    for(int i=1;i<n;i++)
    {
        scanf("%d %d",&u,&v);
        G[u].push_back(v);
        G[v].push_back(u);
    }
}

void dfs(int u,int v,int depth)
{
    a[v]=depth;
    for(int i=0;i<G[v].size();i++)
    {
        int vv=G[v][i];
        if(vv==u)  continue;
        dfs(v,vv,depth+1);
    }
}

void solve()
{
    int Max=-1,c=0,t;
    dfs(-1,1,0);
    for(int i=1;i<=n;i++)   if(Max<a[i]) Max=a[i],c=i;
    Max=-1;
    memset(a,0,sizeof(a));
    dfs(-1,c,0);
    for(int i=1;i<=n;i++)  Max=max(Max,a[i]);
    for(int i=0;i<m;i++)
    {
        scanf("%d",&t);
        if(t<=Max+1)  printf("%d\n",t-1);
        else   printf("%d\n",2*(t-Max-1)+Max);
    }
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        initial();
        input();
        solve();
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章