(DP求最长路) hdu 4607

Park Visit

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


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
 
Source
 
Recommend
liuyiding   |   We have carefully selected several similar problems for you:  5227 5226 5225 5224 5223 
 
 
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<vector>
using namespace std;
vector<int> e[100005];
int n,m,dist[100005],k;
void dfs(int u,int father)
{
    for(int i=0;i<e[u].size();i++)
    {
        int v=e[u][i];
        if(v==father)
            continue;
        dist[v]=dist[u]+1;
        dfs(v,u);
    }
}
int main()
{
    int tt;
    scanf("%d",&tt);
    while(tt--)
    {
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
            e[i].clear();
        for(int i=1;i<n;i++)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            e[x].push_back(y);
            e[y].push_back(x);
        }
        memset(dist,0,sizeof(dist));
        dfs(1,-1);
        int len=0,u;
        for(int i=1;i<=n;i++)
        {
            if(dist[i]>len)
            {
                len=dist[i];
                u=i;
            }
        }
        memset(dist,0,sizeof(dist));
        dfs(u,-1);
        len=0;
        for(int i=1;i<=n;i++)
        {
            if(dist[i]>len)
                len=dist[i];
        }
        len++;
        while(m--)
        {
            scanf("%d",&k);
            if(len>=k)
            {
                printf("%d
",k-1);
            }
            else
            {
                printf("%d
",(k-len)*2+len-1);
            }
        }
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/water-full/p/4493956.html