USACO 2008 Jan Gold 3.Cell Phone Network 树形dp


DPif[i]g[i]h[i]
f[i]=min(f[j],g[j],h[j])json[i]
g[i]=min(f[j],g[j])+min(f[j]min(f[j],g[j]))json[i]
h[i]=g[j] 没什么了,只能是这样了
下面是代码

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#define inf 0x3f3f3f
#define min(a,b) ((a)<(b)?(a):(b))
#define N 10000+5
#define M 20000+5
using namespace std;
int head[N],f[N],g[N],h[N],n;
struct graph 
{   
    int next,to;
    graph () {}
    graph (int _next,int _to)
    :next(_next),to(_to){}
}edge[M];
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0' || ch>'9'){if(ch=='-1')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
    return x*f;
}
inline void add(int x,int y)
{
    static int cnt = 0;
    edge[++cnt]=graph(head[x],y);
    head[x]=cnt;
    edge[++cnt]=graph(head[y],x);
    head[y]=cnt;
}
void DFS(int x,int fa)
{
    f[x]=1;g[x]=0;
    int MIN=inf;
    for(int i=head[x];i;i=edge[i].next)
        if(edge[i].to ^ fa)
        {
            DFS(edge[i].to,x);
            f[x]+=min(f[edge[i].to],min(g[edge[i].to],h[edge[i].to]));
            g[x]+=min(f[edge[i].to],g[edge[i].to]);
            MIN=min(MIN,f[edge[i].to]-min(f[edge[i].to],g[edge[i].to]));
            h[x]+=g[edge[i].to];
        }
    g[x]+=MIN;
}
int main()
{
    cin>>n;
    for(int i=1;i<n;++i)
    {
        int tmp1=read(),tmp2=read();
        add(tmp1,tmp2);
    }
    DFS(1,-1);
    cout<<min(f[1],g[1]);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值