hdu 4607
题目:http://acm.hdu.edu.cn/showproblem.php?pid=4607
思路:今天下午这道题想了很久,其他队伍都出了好久了,我们还没想到,最先开始想到的是三维的树形DP,但是时间、空间都伤不起。最后还是问了下别人才知道的,原来只要求树上的最长链就好了,看来 YY 能力不行啊。。= =
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN = 111111 ;
struct Edge
{
int t,next;
} edge[MAXN<<1];
int tot,head[MAXN];
void add_edge(int s,int t)
{
edge[tot].t=t;
edge[tot].next = head[s];
head[s] = tot++;
}
int num[MAXN];
int maxx;
void dfs(int u,int fa)
{
num[u]=1;
int m1 = 0,m2 = 0;
for(int e = head[u];e!=-1;e = edge[e].next)
{
int v = edge[e].t;
if(v!=fa)
{
dfs(v,u);
if(num[v]>m1)
{
m2 = m1;
m1 = num[v];
}
else if(num[v]>m2)
{
m2 = num[v];
}
}
}
num[u]=m1+1;
maxx = max(maxx,m1+m2+1);
//printf("u = %d,maxx = %d,m1 = %d,m2 = %d\n",u,maxx,m1,m2);
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int n,m;
scanf("%d%d",&n,&m);
int a,b;
tot=0;
memset(head,-1,sizeof(head));
for(int i=1;i<n;i++)
{
scanf("%d%d",&a,&b);
add_edge(a,b);
add_edge(b,a);
}
maxx=0;
dfs(1,-1);
//printf("maxx = %d\n",maxx);
while(m--)
{
int x;
scanf("%d",&x);
if(x<=maxx)
{
printf("%d\n",x-1);
}
else
{
printf("%d\n",(x-maxx)*2+maxx-1);
}
}
}
return 0;
}