Cell Phone Network(最小支配集)

题目描述
Farmer John has decided to give each of his cows a cell phone in hopes to encourage their social interaction. This, however, requires him to set up cell phone towers on his N (1 ≤ N ≤ 10,000) pastures (conveniently numbered 1…N) so they can all communicate.

Exactly N-1 pairs of pastures are adjacent, and for any two pastures A and B (1 ≤ A ≤ N; 1 ≤ B ≤ N; A ≠ B) there is a sequence of adjacent pastures such that A is the first pasture in the sequence and B is the last. Farmer John can only place cell phone towers in the pastures, and each tower has enough range to provide service to the pasture it is on and all pastures adjacent to the pasture with the cell tower.

Help him determine the minimum number of towers he must install to provide cell phone service to each pasture.

John想让他的所有牛用上手机以便相互交流(也是醉了。。。),他需要建立几座信号塔在N块草地中。已知与信号塔相邻的草地能收到信号。给你N-1个草地(A,B)的相邻关系,问:最少需要建多少个信号塔能实现所有草地都有信号。
输入格式

  • Line 1: A single integer: N

  • Lines 2…N: Each line specifies a pair of adjacent pastures with two space-separated integers: A and B

AC代码

#include <iostream>
#include <string.h>
using namespace std;
const int inf=0x3f3f3f3f;
const int MAX_N=10001;
const int MAX_M=20001;

int dp[MAX_N][3];
int n;

int head[MAX_N];
int ans=0;
struct edge{
    int v;
    int next;
}eid[MAX_M];

void insert(int u,int v){
    eid[ans].v=v;
    eid[ans].next=head[u];
    head[u]=ans++;
}
void dfs(int node,int father){
    bool leaf= true;
    dp[node][0]=1;
    dp[node][1]=0;
    dp[node][2]=0;
    int inc=inf;
    int flag=0;
    for(int i=head[node];i!=-1;i=eid[i].next){
        int v=eid[i].v;
        if(v==father) continue;
        dfs(v,node);
        leaf= false;
        dp[node][0]+=min(min(dp[v][0],dp[v][1]),dp[v][2]);
        if(dp[v][1]!=inf && dp[node][2]!=inf) {
            dp[node][2] += dp[v][1];
        }
        else{
            dp[node][2]=inf;
        }

        if(dp[v][0]<dp[v][1]){
            flag=1;
            dp[node][1]+=dp[v][0];
        }
        else{
            dp[node][1]+=dp[v][1];
            inc=min(inc,dp[v][0]-dp[v][1]);
        }
    }

    if(leaf){
        dp[node][1]=inf;
    }
    else{
        if(!flag){
            dp[node][1]+=inc;
        }
    }
}
int main() {
    memset(head,-1, sizeof(head));

    scanf("%d",&n);
    int u,v;
    for(int i=1;i<n;++i){
        scanf("%d%d",&u,&v);
        insert(u,v);
        insert(v,u);
    }

    dfs(1,-1);
    cout<<min(dp[1][0],dp[1][1]);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值