hdu3534 树形DP+方案数

看到这个题目联想到了2169,前面的最长距离很好求,麻烦的就是求路径数,一开始想直接相加再除二发现不对,苦思无奈之下看了解题报告,顿时恍然大悟。。。

求方案数可以通过标记来统计,很好的树形DP题目,标程及解题报告上传到CSDN资源了。

通过这个题目发现了自己的缺点:

1.考虑不全面;

2.代码实现技巧仍需很大提高;

3.细节没考虑好,没思考清楚就急于敲代码;

 

ACcode:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int nsize=11111;

struct tre
{
    int w,to,next;
}c[nsize<<1];

struct Node
{
    int num,sum_num;
    int len,sum_len;
}node[nsize];

int n,p,q,k,m[2];
int head[nsize],vis[nsize],top;

void add(int fa,int s,int w)
{
    c[top].w=w;
    c[top].to=s;
    c[top].next=head[fa];
    head[fa]=top++;
}

void dfs(int r)
{
    int a,b,to;
    int son_max=-1,son_num=0;
    int total,first_num;
    int p[2]={0,0},q[2]={1,0};
    total=vis[r]=first_num=1;

    for (int i=head[r];i!=-1;i=c[i].next)
    {
        to=c[i].to;
        if (vis[to]) continue;
        dfs(to);
        a=node[to].len+c[i].w;
        b=node[to].num;

        if (a>p[0])
        {
            p[1]=p[0],q[1]=q[0];
            p[0]=a,q[0]=b;
            first_num=1;
            total=q[0]*q[1];
        }
        else if (a==p[0])
        {
            if (first_num==1)
                total=0;
            first_num++;
            total+=q[0]*b;
            q[0]+=b;
        }
        else if (a>p[1])
        {
            p[1]=a,q[1]=b;
            if (first_num==1)
                total=q[0]*q[1];
        }
        else if (a==p[1])
        {
            q[1]+=b;
            if (first_num==1)
                total=q[0]*b;
        }

        a=node[to].sum_len;
        b=node[to].sum_num;
        if (a>son_max)
        {
            son_max=a;
            son_num=b;
        }
        else if (a==son_max)
        {
            son_num+=b;
        }
    }

    a=p[0]+(first_num>1? p[0]:p[1]);
    b=total;

    if (a<son_max)
    {
        a=son_max;
        b=son_num;
    }
    else if (a==son_max)
    {
        a=son_max;
        b=son_num+total;
    }

    node[r].len=p[0];
    node[r].num=q[0];
    node[r].sum_len=a;
    node[r].sum_num=b;
}

int main()
{
    while (~scanf("%d",&n))
    {
        top=0;
        memset(vis,0,sizeof(vis));
        memset(node,0,sizeof(node));
        memset(head,-1,sizeof(head));
        for (int i=1;i<n;i++)
        {
            scanf("%d %d %d",&p,&q,&k);
            add(p,q,k),add(q,p,k);
        }
        dfs(1);
        printf("%d %d\n",node[1].sum_len,node[1].sum_num);
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值