洛谷2279(贪心)

每次寻找最大深度的节点,若未被覆盖则将其爷爷设为站点并更新父辈的距离。
其中\(d[i]\)是该点的深度,\(dis[i]\)是它到最近的消防站的距离。

#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn = 1e3 + 5;
int n, f[maxn], ans;
int d[maxn], b[maxn], dis[maxn];

int main() {
	scanf("%d", &n);
	for (int i = 2; i <= n; i++) {
		scanf("%d", &f[i]);
		d[i] = d[f[i]] + 1;
	}
	for (int i = 0; i <= n; i++) {
		b[i] = i;
		dis[i] = maxn;
	}
	sort(b + 1, b + 1 + n, [](int x, int y){ return d[x] > d[y]; });
	for (int i = 1; i <= n; i++) {
		int cur = b[i], fa = f[cur], gf = f[fa];
		dis[cur] = min(dis[cur], min(dis[fa] + 1, dis[gf] + 2));
		if (dis[cur] > 2) {
			ans++;
			dis[gf] = 0;
			dis[f[gf]] = min(dis[f[gf]], 1);
			dis[f[f[gf]]] = min(dis[f[f[gf]]], 2);
		}
	}
	return !printf("%d\n", ans);
}
posted @ 2019-05-13 14:53  AlphaWA  阅读(195)  评论(0编辑  收藏  举报