CodeForces-682C(DFS,树,思维)

链接:

https://vjudge.net/problem/CodeForces-682C

题意:

Alyona decided to go on a diet and went to the forest to get some apples. There she unexpectedly found a magic rooted tree with root in the vertex 1, every vertex and every edge of which has a number written on.

The girl noticed that some of the tree's vertices are sad, so she decided to play with them. Let's call vertex v sad if there is a vertex u in subtree of vertex v such that dist(v, u) > au, where au is the number written on vertex u, dist(v, u) is the sum of the numbers written on the edges on the path from v to u.

Leaves of a tree are vertices connected to a single vertex by a single edge, but the root of a tree is a leaf if and only if the tree consists of a single vertex — root.

Thus Alyona decided to remove some of tree leaves until there will be no any sad vertex left in the tree. What is the minimum number of leaves Alyona needs to remove?

思路:

给了一个有根树,那就建个有向图就行了,第一遍Dfs找到每个要删除的点,同时计算每个点的子节点有多少.
第二遍dfs把遇到的第一个要删的点,删除,同时他的子节点也要删除,因为可能出现根节点删除,子节点不删的情况.
所以直接统计根加子节点的数目一并删除.找满足删的点的时候要考虑是到他的任一祖先都满足,所以用一点dp的思想,
dis(u) 为到u点的最长值,dis(u) = max(dis(v)+w, w),不断更新即可.

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
//#include <memory.h>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
#include <stack>
#include <string>
#include <assert.h>
#define MINF 0x3f3f3f3f
using namespace std;
typedef long long LL;

const int MAXN = 1e5+10;
struct Node
{
    int to;
    LL w;
};
LL Value[MAXN];
vector<Node> G[MAXN];
int Vis[MAXN], Sum[MAXN];
int n, cnt = 0;

int Dfs(int x, LL v)
{
    int res = 1;
    for (int i = 0;i < G[x].size();i++)
    {
        int to = G[x][i].to;
        res += Dfs(to, max(v+G[x][i].w, G[x][i].w));
    }
    if (v > Value[x])
        Vis[x] = 1;
    Sum[x] = res;
    return res;
}

void Dfs2(int x)
{
    for (int i = 0;i < G[x].size();i++)
    {
        if (Vis[G[x][i].to])
            cnt += Sum[G[x][i].to];
        else
            Dfs2(G[x][i].to);
    }
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int v, w;
    cin >> n;
    for (int i = 1;i <= n;i++)
        cin >> Value[i];
    for (int i = 1;i < n;i++)
    {
        cin >> v >> w;
        G[v].push_back(Node{i+1, w});
    }
    Sum[1] = Dfs(1, 0);
    Dfs2(1);
    cout << cnt << endl;

    return 0;
}

转载于:https://www.cnblogs.com/YDDDD/p/11363040.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值