hdoj1520(树型dp)

1.vector孩子结点表示法(原)

#include<iostream>
#include<cstdio>
#include<string.h>
#include<vector>
using namespace std;
//   freopen("data.in","r",stdin);




struct Node
{
    int v;
    int is,no;
    vector<int> son;
} a[6010];
void search(int r)
{
    int s;
    for(unsigned int i=0; i<a[r].son.size(); i++)
    {
        s=a[r].son[i];
        search(s);
        a[r].is+=a[s].no;
        a[r].no+=max(a[s].no,a[s].is);
    }
}
bool f[6010];




int main()
{
 //   freopen("data.in","r",stdin);




    int n;
    while(cin>>n)
    {
        memset(f,0,sizeof(f));
        int son,father;
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&a[i].v);
            a[i].is=a[i].v;
            a[i].no=0;
            a[i].son.clear();
        }
        while(scanf("%d%d",&son,&father),son+father)
        {
            a[father].son.push_back(son);
            f[son]=1;
        }
        for(int i=1; i<=n; i++)
        {
            if(!f[i])
            {
                search(i);
                cout<<max(a[i].is,a[i].no)<<endl;
                break;
            }
        }
    }
    return 0;
}



1.父兄孩子结点表示法(参考http://www.cppblog.com/notonlysuccess/archive/2009/05/11/82614.html)
在图里的邻接表(前向星)表示是一个原理,树是图的特殊情况!
#include<iostream>
#include<cstdio>
#include<string.h>
#include<vector>
using namespace std;
//   freopen("data.in","r",stdin);




struct Node
{
    int is,no;
    int father,brother,child;
    void init()
    {
        father=child=no=brother=0;
    }
} a[6010];
void dfs(int r)
{
    int child=a[r].child;
    while(child)
    {
        dfs(child);
        a[r].is+=a[child].no;
        a[r].no+=max(a[child].is,a[child].no);
        child=a[child].brother;
    }
}




int main()
{
//   freopen("data.in","r",stdin);
    int n;
    while(cin>>n)
    {
        int son,father;
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&a[i].is);
            a[i].init();
        }




        while(scanf("%d%d",&son,&father),son+father)
        {
            a[son].brother=a[father].child;
            a[father].child=son;
            a[son].father=father;
        }
        for(int i=1; i<=n; i++)
        {
            if(!a[i].father)
            {
                dfs(i);
                cout<<max(a[i].is,a[i].no)<<endl;
                break;
            }
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值