点击打开题目
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 3216 Accepted Submission(s): 1449
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≤10 5), 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
2013 Multi-University Training Contest 1
这道题还是变型求树的直径,可能一次观察不出来。
如果 Q <= maxx(表示树的直径),那么就输出 Q - 1 ;
否则,输出 2 * Q - maxx - 1。
下面说一下原因,如果Q比直径小,那么肯定走直径那条路就够了。
如果Q比直径大,也就说得走到分支上,但是我们的主干道还是直径那条路,直径上与分支路的交叉点要走两次,也就说,我们在把树的直径走完了,再在分支上走了Q - maxx 个地点,然后在交叉点出重复多走了Q次,所以结果就是他们加起来 2 * Q - maxx ,最后减1就行了。
代码如下:
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define MAX 100000
vector<int> mapp[MAX+11];
int f[MAX+11];
bool vis[MAX+11];
int n,m;
void init()
{
for (int i = 1 ; i <= n ; i++)
mapp[i].clear();
}
int dfs(int x)
{
queue<int> q;
CLR(vis,false);
CLR(f,0);
q.push(x);
vis[x] = true;
f[x] = 1;
int maxx = 0;
int ans = x;
while (!q.empty())
{
int ne = q.front();
q.pop();
for (int i = 0 ; i < mapp[ne].size() ; i++)
{
if (!vis[mapp[ne][i]])
{
q.push(mapp[ne][i]);
vis[mapp[ne][i]] = true;
f[mapp[ne][i]] = f[ne] + 1;
if (f[mapp[ne][i]] > maxx)
{
maxx = f[mapp[ne][i]];
ans = mapp[ne][i];
}
}
}
}
return ans;
}
int main()
{
int u;
scanf ("%d",&u);
while (u--)
{
scanf ("%d %d",&n,&m);
init();
for (int i = 1 ; i < n ; i++)
{
int t1,t2;
scanf ("%d %d",&t1,&t2);
mapp[t1].push_back(t2);
mapp[t2].push_back(t1);
}
int pos = dfs(1);
pos = dfs(pos); //最长链的下标
int maxx = f[pos]; //最长链
while (m--)
{
int t;
scanf ("%d",&t);
if (t <= maxx)
printf ("%d\n",t - 1);
else
printf ("%d\n",2*t - maxx - 1);
}
}
return 0;
}