bzoj 1217 [HNOI2003]消防局的设立 贪心
题面
解法
树形dp表示感觉太烦,不太会写
考虑贪心
显然每一次应该选深度最大且没有被覆盖的点,然后找到它的爷爷,然后暴力更新
当然,距离大一点贪心也是正确的
时间复杂度:\(O(n)\)
代码
#include <bits/stdc++.h>
#define N 100010
using namespace std;
template <typename node> void chkmax(node &x, node y) {x = max(x, y);}
template <typename node> void chkmin(node &x, node y) {x = min(x, y);}
template <typename node> void read(node &x) {
x = 0; int f = 1; char c = getchar();
while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
struct Edge {
int next, num;
} e[N * 3];
int n, k, t, cnt, d[N], vis[N], fa[N];
void add(int x, int y) {
e[++cnt] = (Edge) {e[x].next, y};
e[x].next = cnt;
}
void bfs() {
queue <int> q; q.push(1);
int len = 1; d[1] = 1; fa[1] = 1;
while (!q.empty()) {
int x = q.front(); q.pop();
for (int p = e[x].next; p; p = e[p].next) {
int k = e[p].num;
if (fa[k]) continue;
d[++len] = k, q.push(k);
fa[k] = x;
}
}
}
void dfs(int x, int fa, int s) {
vis[x] = 1; if (s == k) return;
for (int p = e[x].next; p; p = e[p].next) {
int k = e[p].num;
if (k != fa) dfs(k, x, s + 1);
}
}
int main() {
read(n); cnt = n, k = 2;
for (int i = 2; i <= n; i++) {
int x; read(x);
add(x, i), add(i, x);
}
bfs(); int ans = 0;
for (int i = n; i; i--)
if (!vis[d[i]]) {
int x = d[i]; ans++;
for (int j = k; j; j--) x = fa[x];
dfs(x, 0, 0);
}
cout << ans << "\n";
return 0;
}