---
id: 94
lang: en
translation_of: index.md
source_sha256: ece4d2891f82c5d45ad07d824e1dee5544a978772c5e7b49a3c1ed268df0f80e
title: "P2279: [HNOI2003] Setting Up Fire Stations — Solution"
description: "Sort the tree's nodes by depth and, for each uncovered node from the deepest up, put a fire station at its grandparent."
tags: ["OI","Graph Theory","Trees","Provincial Team Selection","Minimum Cover","Greedy"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "爷爷节点 rendered as “grandparent node” (standard tree term, no chip)."
---

## Idea

The data structure given in the problem statement is quite obviously a tree, and we need to find the minimum number of fire stations that can cover the whole tree. We first read the input as required, decide on the root (here I use node 1), then sort by depth and start checking from the deepest node. If a node is not covered, we cover its grandparent node, which maximizes the covered area; while covering, we spread out in both directions and set the vis[i] mark. Marked nodes are skipped, and for an unmarked node we put the fire station at its grandparent. Since our placement proceeds step by step from deep to shallow by depth, there won't be any hidden problems.

## Code

```cpp
// P2279.cpp
#include <iostream>
#include <stack>
#include <queue>
using namespace std;

const int maxn = 4040;

struct edge
{
    int to, next;
} edges[maxn];
int head[maxn];
int F[maxn];
stack<int> st;
bool vis[maxn];
int current = 0;
int n;

void addpath(int src, int dst)
{
    edges[current].to = dst;
    edges[current].next = head[src];
    head[src] = current++;
}

void BFS()
{
    queue<int> q;
    q.push(1);
    st.push(1);
    while (!q.empty())
    {
        int curt = q.front();
        q.pop();
        for (int i = head[curt]; i != -1; i = edges[i].next)
            if (edges[i].to != F[curt])
                st.push(edges[i].to), q.push(edges[i].to);
    }
}

void DFS(int p, int dep)
{
    if (dep > 2)
        return;
    vis[p] = true;
    for (int i = head[p]; i != -1; i = edges[i].next)
        DFS(edges[i].to, dep + 1);
}

int main()
{
    cin >> n;
    fill(head, head + maxn, -1);
    fill(vis, vis + maxn, false);
    int num = -1;
    for (int i = 2; i <= n; i++)
    {
        cin >> num;
        F[i] = num;
        addpath(num, i), addpath(i, num);
    }
    // going to solve;
    BFS();
    int ans = 0;
    while (!st.empty())
    {
        int curt = st.top();
        st.pop();
        if (!vis[curt] && ++ans)
            DFS(F[F[curt]], 0);
    }
    cout << ans;
    return 0;
}
```
