Title [brush] [greedy] [tree] established fire station

A tree, n bases

Each has the ability to extinguish the fire station and its distance from the base of no more than 2 fire.

Your task is to build at least calculate how many fire stations to be able to ensure that all bases on Mars in the event of a fire, the fire department has the ability to put out the fire. ,

 

(Luogu)

This problem greedy and wanted to compare

Consider the current maximum depth of leaf nodes, you are sure to have a fire station to cover it,

So since he is a leaf node, so he and the distance is less than equal to node 2 are just a few:

  1. His father, his brothers 2. 3. His grandfather

Readily seen, the two nodes can cover the front, where the establishment must also grandfather can cover.

So every greedy remove the maximum depth of the node, where his grandfather put a fire station

 

#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
using namespace std;
int n;
const int N=1003;
int fa[N],dep[N],xl[N];
bool cmp(int a,int b)
{ return dep[a]<dep[b]; }

int tot,head[N];
int ev[N<<1],enx[N<<1];
void add(int u,int v)
{ ev[++tot]=v,enx[tot]=head[u],head[u]=tot; }

bool hav[N];
int ans;
void dfs(int st,int pre,int ll)
{
    hav[st]=true;
    if(ll==2 ) return ;
    
    for(int i=head[st];i;i=enx[i])
        if(ev[i]!=pre )
            dfs(ev[i],st,ll+1);
}

int main()
{
    scanf("%d",&n);
    int x;
    for(int i=2;i<=n;i++)
        scanf("%d",&x),fa[i]=x,add(x,i),add(i,x);
    for(int i=1;i<=n;i++)
        dep[i]=dep[fa[i]]+1,xl[i]=i;
    sort(xl+1,xl+n+1,cmp);
    
    for(int i=n;i;i--)
    {
        if(hav[xl[i]]) continue;
        
        int v=xl[i];
        if(fa[v]) v=fa[v];
        if(fa[v]) v=fa[v];
        ans++;
        
        dfs(v,0,0);
    }
    printf("%d\n",ans);
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/xwww666666/p/11721693.html
Recommended