HDU 4607 Park Visit(树的直径)

题意:

N105,M105KN

分析:

1,2,

代码:

//
// Created by TaoSama on 2016-02-25
// Copyright (c) 2016 TaoSama. All rights reserved.
//
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>

using namespace std;
#define pr(x) cout << #x << " = " << x << " "
#define prln(x) cout << #x << " = " << x << endl
const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;

int n, q;
vector<int> G[N];

pair<int, int> diameter;

void dfs(int u, int f, int d) {
    diameter = max(diameter, {d, u});
    for(int v : G[u]) {
        if(v == f) continue;
        dfs(v, u, d + 1);
    }
}

int main() {
#ifdef LOCAL
    freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin);
// freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout);
#endif
    ios_base::sync_with_stdio(0);

    int t; scanf("%d", &t);
    while(t--) {
        scanf("%d%d", &n, &q);
        for(int i = 1; i <= n; ++i) G[i].clear();
        for(int i = 1; i < n; ++i) {
            int u, v; scanf("%d%d", &u, &v);
            G[u].push_back(v);
            G[v].push_back(u);
        }
        diameter = { -1, -1};
        dfs(1, -1, 1);
        dfs(diameter.second, -1, 1);
        int d = diameter.first;
        while(q--) {
            int k; scanf("%d", &k);
            if(d >= k) printf("%d\n", k - 1);
            else printf("%d\n", d - 1 + (k - d) * 2);
        }
    }
    return 0;
}

你可能感兴趣的:(树的直径)