现在的位置: 首页 > 综合 > 正文

HDU 4607 Park Visit

2013年01月13日 ⁄ 综合 ⁄ 共 2096字 ⁄ 字号 评论关闭

Park Visit

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


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
 
题意:有N个节点, N-1条边 , 每条边的长度为1, 问到达K个节点, 最少需要走多远的路。
思路: 求树的直径 (广搜两遍)
遍历一颗树首先不会超过 2 * N次。
因为在最长路里,每多走一个节点只需要走一条边,  而其他几点都需要经过两次。
所以在K <= 最长路包括的点  答案就是 k - 1 ;
在K > 最长路包括的点, 答案是 最长路 + (k - 最长路) * 2;
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

const int V = 100000 + 50;
const int MaxN = 100000 + 5;
const int mod = 1000000000 + 7;
int T, N, M, ans, last;
bool visit[V];
vector<int> vec[V];
void bfs(int index, int len) {
    visit[index] = true;
    if(len > ans) {
        ans = len;
        last = index;
    }
    int last = -1;
    for(int i = 0; i < vec[index].size(); ++i)
        if(!visit[vec[index][i]])
            bfs(vec[index][i], len + 1);
}
int main() {
    int i, j;
    scanf("%d", &T);
    while(T--) {
        scanf("%d%d", &N, &M);
        for(i = 1; i <= N; ++i)
            vec[i].clear();
        for(i = 1; i <= N - 1; ++i) {
            int a, b;
            scanf("%d%d", &a, &b);
            vec[a].push_back(b);
            vec[b].push_back(a);
        }
        ans = 0;
        memset(visit, false, sizeof(visit));
        bfs(1, 1);
        ans = 0;
        memset(visit, false, sizeof(visit));
        bfs(last, 1);
        while(M--) {
            int k;
            scanf("%d", &k);
            if(k <= ans)
                printf("%d\n", k - 1);
            else
                printf("%d\n", ans - 1 + (k - ans) * 2);
        }
    }
}

抱歉!评论已关闭.