题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4607
题意:
有一棵树,n结点n-1条边,接下来有m个提问,对于每一个提问,有一个数k,表示能经过k个结点。输出一个数,即能经过k个结点的最小距离(有边连接的两个点边权为1)
题解:
这个题目解法并不是很难,主要就是很难想到。
首先,因为我们只需要考虑k-1个结点(因为有1个结点已经走到了),所以我们先让k–,
其次,我们考虑一条这棵树上的最长路径,不妨设这条路径的长度为 ans,如果当前这个k(已经 – 后的) <= ans,则直接输出k
否则,我们答案就是ans+(k-ans)*2。
为什么呢?
我们可以发现,如果最长路的长度 < k,那么其中必有一些所谓“分叉”,而每走一个分叉,需要增加(分叉节点数*2)步。
我们需要增加k-ans个,所以需要增加(k-ans)*2步。加上原有的结果,就是答案。
下面讨论如何实现:
最长路=从最深的点开始求最长路。
最深的点可以从root跑一遍最长路。
刚开始我还想用floyd。。看到数据就被吓到了。
好吧还是用spfa吧。。
贴上以前的模板,调调过了样例,交上去TLE了。
后来又重写了一遍才AC。。
代码:
// by DenyTianly
#include <set>
#include <map>
#include <list>
#include <queue>
#include <stack>
#include <deque>
#include <ctime>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
#define iScf(n) scanf("%d", &n)
#define dug() printf("ok!\n")
#define iNxtL() puts("")
#define rep(i, n) for(int i = 0; i < n; i++)
#define rrep(i, n) for(int i = n-1; i >= 0; i--)
#define nrep(i, val, n) for(int i = val; i < n; i++)
#define ipq priority_queue
typedef long long LL;
typedef unsigned long long ULL;
const int inf = 1 << 26;
const LL INF = 1LL << 60;
inline void quick_IO() { ios::sync_with_stdio(false); cout.tie(0); cin.tie(0); }
inline int read(){
int x = 0, f = 1;
char ch = getchar();
for(; ch < '0' || ch > '9'; ch = getchar())
if(ch == '-') f = -f;
for(; ch >= '0' && ch <= '9'; ch = getchar())
x = x*10+ch-'0';
return x*f;
}
int quick_pow(int a, int b) { // calculate a^b
if(b == 1) return a;
int temp = quick_pow(a, b/2);
if(b&1) return temp*temp*a;
else return temp*temp;
}
// Don't hack me, please ~
// #define _Isopen_File_
// #define _Is_Close_STD_
const int size = 3e5+5;
int ans = 0,cnt=0,n,m;
int dis[size], head[size],vis[size], poi = 0;
struct edges {
int v, w, next;
} ed[size*2];
void add(int x, int y, int z) {
ed[cnt].v = y;
ed[cnt].w = z;
ed[cnt].next = head[x];
head[x] = cnt ++;
}
queue<int> q;
void spfa(int sta) {
while(!q.empty()) q.pop();
memset(vis, 0, sizeof(vis));
for ( int i = 1; i <= n; i ++ ) dis[i] = inf;
dis[sta] = 0;
vis[sta] = 1;
q.push(sta);
while(!q.empty()) {
int fr = q.front(); q.pop();
vis[fr] = 1;
for (int th = head[fr]; th != -1; th = ed[th].next) {
if(dis[ed[th].v] > dis[fr]+ed[th].w) {
dis[ed[th].v] = dis[fr]+ed[th].w;
if(!vis[ed[th].v]) {
vis[ed[th].v] = 1;
q.push(ed[th].v);
}
}
}
}
ans = 0;
for ( int i = 1; i <= n; i ++ ) {
if(ans < dis[i]) {
ans = dis[i];
poi = i;
}
}
}
int main(){
// freopen("4706.in","r",stdin);
int tst;
scanf("%d", &tst);
while( tst--){
cnt = 0;
poi = 0;
memset(head,-1,sizeof(head));
scanf("%d %d", &n, &m);
for ( int i = 0; i < n-1; i ++ ) {
int x, y;
scanf("%d %d", &x, &y);
add(x, y, 1);
add(y, x, 1);
}
spfa(1);
spfa(poi);
for ( int i = 0; i < m; i ++) {
int k;
scanf("%d", &k);
k--;
if(k < ans) printf("%d\n", k);
else printf("%d\n", ans+2*(k-ans));
}
}
return 0;
}