您的位置:首页 > 编程语言 > C语言/C++

HDU 4607 Park Visit

2016-11-09 23:59 246 查看
[align=left]Problem Description[/align]
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?

 

[align=left]Input[/align]
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.

 

[align=left]Output[/align]
For each query, output the minimum walking distance, one per line.
 

[align=left]Sample Input[/align]

1
4 2
3 2
1 2
4 2
2
4

 

[align=left]Sample Output[/align]

1
4

 

[align=left]Source[/align]
2013 Multi-University
Training Contest 1
 

[align=left]Recommend[/align]
liuyiding

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

SPFA~

两次遍历求直径,类似模板~

#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;

int t,n,m,x,y,k,fi[200010],cnt,dis[100005],tot,num,maxx;
bool b[100005];
queue<int> q;

struct node{
int w,ne;
}a[200010];

void add(int u,int v)
{
a[++cnt].w=v;a[cnt].ne=fi[u];fi[u]=cnt;
}

void spfa(int u)
{
for(int i=1;i<=n;i++) dis[i]=0xffffff;
q.push(u);dis[u]=0;b[u]=1;
while(!q.empty())
{
int kkz=q.front();q.pop();b[kkz]=0;
for(int i=fi[kkz];i!=-1;i=a[i].ne)
if(dis[a[i].w]>dis[kkz]+1)
{
dis[a[i].w]=dis[kkz]+1;
if(!b[a[i].w])
{
b[a[i].w]=1;q.push(a[i].w);
}
}
}
}

int main()
{
scanf("%d",&t);
while(t--)
{
memset(fi,-1,sizeof(fi));
scanf("%d%d",&n,&m);
for(int i=1;i<n;i++)
{
scanf("%d%d",&x,&y);
add(x,y);add(y,x);
}
spfa(1);maxx=num=-1;
for(int i=1;i<=n;i++)
if(dis[i]>maxx)
{
maxx=dis[i];num=i;
}
spfa(num);maxx=-1;
for(int i=1;i<=n;i++) maxx=max(maxx,dis[i]);
while(m--)
{
scanf("%d",&k);
if(k<=maxx+1) printf("%d\n",k-1);
else printf("%d\n",(k-maxx-1)*2+maxx);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ SPFA