hdu 4607 Park Visit(树型DP)

        题意:给出一个树,问访问树上k个点,最少需要走多少距离。

        思路:要让路径最短,那么就应该尽可能少的走重复路径。求出最长边,如果要访问的点小于最长边上的点,那么走的路径长度就是k-1(因为没有回溯)。如果大于最长路径的点,那么要加上剩下的点数*2。

        求最长边的方法我用的是以前做过的一道树形DP的方法:点击打开链接

#include<stdio.h>
#include<string.h>
#define N 100005
struct node
{
    int son;
    int next;
} Edge[N*2];
struct f
{
    int fir;
    int sec;
    int max;
} dp[N];
int head[N],vis[N];
int cnt;
int Max(int x,int y)
{
    if(x>y) return x;
    else return y;
}
void AddEdge(int x,int y)
{
    Edge[cnt].son=y,Edge[cnt].next=head[x],head[x]=cnt++;
    Edge[cnt].son=x,Edge[cnt].next=head[y],head[y]=cnt++;
    return ;
}
void dfs(int father)
{
    int u=head[father];
    vis[father]=1;
    for(int i=u; i!=-1; i=Edge[i].next)
    {
        int son=Edge[i].son;
        if(vis[son]) continue;
        dfs(son);
        int temp;
        dp[father].sec=Max(dp[father].sec,dp[son].fir+1);
        if(dp[father].fir<dp[father].sec)
            temp=dp[father].fir,dp[father].fir=dp[father].sec,dp[father].sec=temp;
    }
    return ;
}
void bfs(int father)
{
    dp[father].max=dp[father].fir+dp[father].sec;
    int u=head[father];
    vis[father]=1;
    for(int i=u; i!=-1; i=Edge[i].next)
    {
        int son=Edge[i].son;
        if(vis[son]) continue;
        if(dp[son].fir+1!=dp[father].fir) dp[son].fir=dp[father].fir+1;
        else
        {
            dp[son].sec=Max(dp[father].sec+1,dp[son].sec);
            int temp;
            if(dp[son].fir<dp[son].sec)
                temp=dp[son].fir,dp[son].fir=dp[son].sec,dp[son].sec=temp;
        }
        bfs(son);
    }
    return ;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int n,m;
        scanf("%d%d",&n,&m);
        int i;
        cnt=0;
        memset(head,-1,sizeof(head));
        for(i=1; i<n; i++)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            AddEdge(x,y);
        }
        memset(dp,0,sizeof(dp));
        memset(vis,0,sizeof(vis));
        dfs(1);
        memset(vis,0,sizeof(vis));
        bfs(1);
        int max=0;
        for(i=1; i<=n; i++)
            max=Max(dp[i].max,max);
        for(i=1; i<=m; i++)
        {
            int x;
            scanf("%d",&x);
            if(x<=max+1) printf("%d\n",x-1);
            else printf("%d\n",max+(x-max-1)*2);
        }
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值