您的位置:首页 > 其它

HDOJ 4607 Park Visit

2014-03-28 19:43 267 查看
树的直径。。。。


Park Visit

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 2225    Accepted Submission(s): 982


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

2013 Multi-University Training Contest 1

 

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>

using namespace std;

const int maxn=150100;

struct Edge
{
int to,next;
}edge[maxn*2];

int n,Q,Adj[maxn],Size;
int dist[maxn];
bool vis[maxn];

void init()
{
Size=0; memset(Adj,-1,sizeof(Adj));
}

void Add_Edge(int u,int v)
{
edge[Size].to=v;
edge[Size].next=Adj[u];
Adj[u]=Size++;
}

int get_diameter()
{
queue<int> q;
memset(vis,0,sizeof(vis));
memset(dist,0,sizeof(dist));
q.push(1); vis[1]=true;
while(!q.empty())
{
int v,u=q.front(); q.pop();
for(int i=Adj[u];~i;i=edge[i].next)
{
v=edge[i].to;
if(vis[v]) continue;
vis[v]=1;dist[v]=dist[u]+1;
q.push(v);
}
}
int goal=-1,mark=-1;
for(int i=1;i<=n;i++)
{
if(dist[i]>mark)
{
mark=dist[i];
goal=i;
}
}

memset(vis,0,sizeof(vis));
memset(dist,0,sizeof(dist));
q.push(goal); vis[goal]=true;
while(!q.empty())
{
int v,u=q.front(); q.pop();
for(int i=Adj[u];~i;i=edge[i].next)
{
v=edge[i].to;
if(vis[v]) continue;
vis[v]=1; dist[v]=dist[u]+1;
q.push(v);
}
}

goal=-1;
for(int i=1;i<=n;i++) goal=max(goal,dist[i]);

return goal;
}

int main()
{
int T_T;
scanf("%d",&T_T);
while(T_T--)
{
scanf("%d%d",&n,&Q);
init();
for(int i=0;i<n-1;i++)
{
int u,v;
scanf("%d%d",&u,&v);
Add_Edge(u,v);
Add_Edge(v,u);
}
int dia=get_diameter();
while(Q--)
{
int x;
scanf("%d",&x);
x--;
if(x<=dia) printf("%d\n",x);
else printf("%d\n",dia+(x-dia)*2);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: