[树形dp-贪心][HNOI2003]消防局的设立

题目:[HNOI2003]消防局的设立

分析:

这题是三星题??不就是个简单贪心吗?好吧,贪心、dp两两不分家,看来刷dp还是能练很多方面的能力的。
很容易的分析出来,对于整棵树最深的叶子结点u,我们肯定选fa[fa[u]],而不选u。这样对于整棵树,我们可以每次选取深度最深的点u,然后染色他的祖父。可以用优先队列实现。

这题竟然是三星???是三星??

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;//三年竞赛一场空,不开long long见祖宗 
//typedef __int128 lll;
#define print(i) cout << "debug: " << i << endl
#define close() ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mem(a, b) memset(a, b, sizeof(a))
#define pb(a) push_back(a)
#define x first
#define y second
typedef pair<int, int> par;
const ll mod = 1e9 + 7;
const int maxn = 1e5 + 10;
const int inf = 0x3f3f3f3f;
struct node
{
    int u, dep;
    node(int u = 0, int dep = 0) : u(u), dep(dep){}
    bool operator< (const node& b) const
    {
        return b.dep > dep;
    }
};
vector<int> g[maxn];
int dep[maxn], fa[maxn];
int vis[maxn];
int n;
int ans;

void dfs1(int u, int f)
{
    if(u != 1) dep[u] = dep[f] + 1;
    fa[u] = f;
    for(int v : g[u])
    {
        if(v == f) continue;
        dfs1(v, u);
    }
}

void dfs2(int u, int f, int cnt)
{
    if(!cnt) return;
    vis[u] = 1;
    for(auto v : g[u])
    {
        if(v == f) continue;
        dfs2(v, u, cnt - 1);
    }
}

void solve()
{
    priority_queue<node> q;
    for(int i = 1; i <= n; i++) q.push(node(i, dep[i]));
    while(!q.empty())
    {
        node now = q.top(); q.pop();
        int u = now.u;
        if(vis[u]) continue;
        ans++;
        int gfa = fa[fa[u]];
        dfs2(gfa, gfa, 3);
    }
}

int main()
{
    cin >> n;
    for(int i = 2; i <= n; i++)
    {
        int x; cin >> x;
        g[i].pb(x), g[x].pb(i);
    }    
    dfs1(1, 1);
    solve();
    cout << ans << endl;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值