洛谷 P2279 [HNOI2003]消防局的设立(贪心???)

本文介绍了一种在树形结构中寻找最少数量消防站的算法,通过深度优先搜索确定每个节点的深度,然后从最深的节点开始设置消防站,确保每个消防站覆盖周围4个单位距离内的节点,最终输出所需最少消防站数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给你一颗树,然后再属相选一些点让他们变成消防站,每个消防站可以控制的距离是2 ,然后问你在这颗树上最少选几个消防站

思路:你从1开始向下搜,把每个点的深度搜索出来,然后排序,因为我们知道,如果一个消防站可以控制的距离是2 ,但是左右就是4了(这个地方我也没想清楚,日后填坑吧),所以我们队深度最大的点开始填消防站,我们向下搜4个深度,然后把路径上的点都打上标记,然后记录搜了几次

代码:

#include <bits/stdc++.h>
using namespace std;

const int maxn=1005;
vector<int>mp[maxn];
struct node
{
    int num,cnt;
    bool operator <(const node &b)const
    {
        if(cnt==b.cnt)return num<b.num;
        return cnt>b.cnt;
    }
};
node stk[maxn];
int top;
int vis[maxn];

void dfs(int x,int pre,int cnt)
{
    node as;
    as.num=x;as.cnt=cnt;
    stk[++top]=as;
    for(int i=0;i<mp[x].size();++i){
        int now=mp[x][i];
        if(now==pre)continue;
        dfs(now,x,cnt+1);
    }
}
void dfs1(int x,int pre,int cnt)
{
    vis[x]=1;
    if(cnt==4)return ;
    for(int i=0;i<mp[x].size();++i){
        int now=mp[x][i];
        if(now==pre)continue;
        dfs1(now,x,cnt+1);
    }
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=2;i<=n;i++){
        int x;
        scanf("%d",&x);
        mp[i].push_back(x);
        mp[x].push_back(i);
    }
    dfs(1,1,0);
    sort(stk+1,stk+1+top);
    int ans=0;
    for(int i=1;i<=top;i++){
        if(vis[stk[i].num])continue;
        ans++;
        dfs1(stk[i].num,0,0);
    }
    printf("%d\n",ans);
    return 0;
}

 

转载于:https://www.cnblogs.com/lalalatianlalu/p/9811834.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值