题目
Description
2020年,人类在火星上建立了一个庞大的基地群,总共有n个基地。起初为了节约材料,人类只修建了n-1条道路来
连接这些基地,并且每两个基地都能够通过道路到达,所以所有的基地形成了一个巨大的树状结构。如果基地A到
基地B至少要经过d条道路的话,我们称基地A到基地B的距离为d。由于火星上非常干燥,经常引发火灾,人类决定
在火星上修建若干个消防局。消防局只能修建在基地里,每个消防局有能力扑灭与它距离不超过2的基地的火灾。
你的任务是计算至少要修建多少个消防局才能够确保火星上所有的基地在发生火灾时,消防队有能力及时扑灭火灾
。
Input
第一行为n,表示火星上基地的数目。N<=1000
接下来的n-1行每行有一个正整数,其中文件第i行的正整数为a[i],表示从编号为i的基地到编号为a[i]的基地之间有一条道路,
为了更加简洁的描述树状结构的基地群,有a[i] < i
Output
仅有一个正整数,表示至少要设立多少个消防局才有能力及时扑灭任何基地发生的火灾。
Sample Input
6
1
2
3
4
5
Sample Output
2
思路
树形dp可以做,可我用的贪心。
每隔4个点放是最优的。
特殊处理一下叶子节点就好了。
代码
#include <bits/stdc++.h>
using namespace std;
const int M = 500000;
struct node { int x, y, nxt; } a[M];
int len, la[M], ans, f[M], n;
inline int read() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if(ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = (x << 1)+(x << 3)+(ch ^ 48);
ch = getchar();
}
return x*f;
}
void adde(int x, int y) {
a[++len].x = x;
a[len].y = y;
a[len].nxt = la[x];
la[x] = len;
}
void treedp(int x,int fa) {
int maxn = -1292371547, minn = -maxn;
for (int k = la[x]; k; k = a[k].nxt) {
int y = a[k].y;
if (y != fa) {
treedp(y, x);
maxn = max(maxn, f[y]);
minn = min(minn, f[y]);
}
}
if(maxn+minn <= 3) f[x] = minn+1;
else f[x] = maxn+1;
if (maxn == -1292371547) f[x] = 3;
if (f[x] == 5) f[x] = 0, ans++;
if (f[x] >= 3 && fa == -1) ans++;
}
int main() {
ios::sync_with_stdio(false);
n = read();
for (int i = 1; i < n; i++) {
int x = read();
adde(i+1,x), adde(x,i+1);
}
treedp(1, -1);
cout << ans << endl;
return 0;
}