题目
Input
Output
仅有一个正整数,表示至少要设立多少个消防局才有能力及时扑灭任何基地发生的火灾。
Sample Input
Sample Output
分析
一道神仙贪心题(QAQ),我们先随意建一棵树,然后经过分析可以得到这样的贪心策略:
我们每次找未被消防站覆盖的点中深度最深的点,在这个点的爷爷建消防站,然后将所有可以覆盖的点打标记,直至所有的点都被覆盖。
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cctype>
#include<cmath>
#include<cstdlib>
#include<queue>
#include<ctime>
#include<vector>
#include<set>
#include<map>
#include<stack>
using namespace std;
struct node{
      int pos,dep;
}d[1100];
vector<int>v[1100];
int fa[1100];
int chose[1100];
void dfs(int x,int f){
      int i,j,k;
      d[x].pos=x;
      for(i=0;i<v[x].size();i++)
         if(v[x][i]!=f){
             fa[v[x][i]]=x;
             d[v[x][i]].dep=d[x].dep+1;
             dfs(v[x][i],x);
         }
      return;
}
bool cmp(const node &x,const node &y){
      return x.dep>y.dep;
}
int main()
{     int n,m,i,j,k,ans=0;
      cin>>n;
      for(i=1;i<n;i++){
          cin>>k;
          v[k].push_back(i+1);
          v[i+1].push_back(k);
      }
      dfs(1,0);
      sort(d+1,d+n+1,cmp);
      for(i=1;i<=n;i++)
         if(!chose[d[i].pos]){
             ans++;
             chose[fa[fa[d[i].pos]]]=1;
             for(j=0;j<v[fa[fa[d[i].pos]]].size();j++){
                chose[v[fa[fa[d[i].pos]]][j]]=1;
                for(k=0;k<v[v[fa[fa[d[i].pos]]][j]].size();k++)
                   chose[v[v[fa[fa[d[i].pos]]][j]][k]]=1;
             }
         }
      cout<<ans<<endl;
      return 0;
}
原文:https://www.cnblogs.com/yzxverygood/p/9026866.html