2013 多校第一场 hdu 4607 Park Visit

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值