2020年,人类在火星上建立了一个庞大的基地群,总共有n个基地。起初为了节约材料,人类只修建了n-1条道路来连接这些基地,并且每两个基地都能够通过
路到达,所以所有的基地形成了一个巨大的树状结构。如果基地A到基地B至少要经过d条道路的话,我们称基地A到基地B的距离为d。
由于火星上非常干燥,经常引发火灾,人类决定在火星上修建若干个消防局。消防局只能修建在基地里,每个消防局有能力扑灭与它距离不超过2的基地的火灾。
你的任务是计算至少要修建多少个消防局才能够确保火星上所有的基地在发生火灾时,消防队有能力及时扑灭火灾。
输入格式:
输入文件名为input.txt。
输入文件的第一行为n (n<=1000),表示火星上基地的数目。接下来的n-1行每行有一个正整数,其中文件第i行的正整数为a[i],表示从编号为i的基地到编号为a[i]的基地之间有一条道路,为了更加简洁的描述树状结构的基地群,有a[i]<i。
输出格式:
输出文件名为output.txt
输出文件仅有一个正整数,表示至少要设立多少个消防局才有能力及时扑灭任何基地发生的火灾。
树形dp没推出转移方程,两遍dfs打了贪心
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn=1e5+5; 4 const int INF=1e9+5; 5 int n,a,b,maxx,mark; 6 int ans,x,d[maxn],f[maxn]; 7 bool vis[maxn]; 8 int head[maxn],tot; 9 struct A 10 { 11 int v,next; 12 }e[maxn]; 13 template <class t>void red(t &x) 14 { 15 x=0; 16 int w=1; 17 char ch=getchar(); 18 while(ch<'0'||ch>'9') 19 { 20 if(ch=='-') 21 w=-1; 22 ch=getchar(); 23 } 24 while(ch>='0'&&ch<='9') 25 { 26 x=(x<<3)+(x<<1)+ch-'0'; 27 ch=getchar(); 28 } 29 x*=w; 30 } 31 void input() 32 { 33 freopen("input.txt","r",stdin); 34 //freopen("output.txt","w",stdout); 35 } 36 struct cmp{ 37 bool operator () (int &a,int &b){ 38 return d[a]<d[b]; 39 } 40 }; 41 priority_queue<int,vector<int>,cmp> q; 42 void add(int x,int y) 43 { 44 e[++tot].v=y; 45 e[tot].next=head[x]; 46 head[x]=tot; 47 } 48 void read() 49 { 50 red(n); 51 for(int i=2;i<=n;++i) 52 { 53 red(a); 54 add(a,i); 55 add(i,a); 56 } 57 } 58 void dfs1(int u,int fa) 59 { 60 d[u]=d[fa]+1; 61 for(int i=head[u];i;i=e[i].next) 62 { 63 int v=e[i].v; 64 if(v==fa) 65 continue; 66 f[v]=u; 67 dfs1(v,u); 68 } 69 } 70 void dfs2(int u,int dep) 71 { 72 if(dep>2) 73 return; 74 vis[u]=1; 75 for(int i=head[u];i;i=e[i].next) 76 { 77 int v=e[i].v; 78 dfs2(v,dep+1); 79 } 80 } 81 void work() 82 { 83 dfs1(1,0); 84 for(int i=1;i<=n;++i) 85 if(d[i]>maxx) 86 { 87 maxx=d[i]; 88 mark=i; 89 } 90 for(int i=1;i<=n;++i) 91 q.push(i); 92 while(!q.empty()) 93 { 94 while(!q.empty()&&vis[x=q.top()]) 95 q.pop(); 96 if(q.empty()) 97 break; 98 if(f[f[x]]) 99 dfs2(f[f[x]],0); 100 else 101 dfs2(1,0); 102 ++ans; 103 } 104 printf("%d",ans); 105 } 106 int main() 107 { 108 //input(); 109 read(); 110 work(); 111 return 0; 112 }