codeforces 682C. Alyona and the Tree

codeforces 682C. Alyona and the Tree

题意

有一颗树,树上的点和边都有权值。要求删除树上若干节点,使得树上每个节点u到其子树上的节点v的 dis(u,v)a(u) 。问最少需要删除多少个节点。

思路

类似与最大连续子段和的思想,对于每个节点是否要保留,在于是否有从根节点方向到以他为结尾的树链的权值比其点权大,有则删除该子树,无则保留该节点。

code

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

#define MAXN (100000 + 5)
#define INF  (999999999)
int n;
int a[MAXN];
int c[MAXN], dp[MAXN], ans;
std::vector<pair<int, int> > v[MAXN];

void CN (int rt) {
  if (v[rt].size() == 0) {
    c[rt] = 1;
    return;
  }
  c[rt] = 1;
  for (int i=0; i<v[rt].size(); i++) {
    CN(v[rt][i].first);
    c[rt] += c[v[rt][i].first];
  }
}

void DP (int rt) {
  if (v[rt].size() == 0) {
    return ;
  }

  for (int i=0; i<v[rt].size(); i++) {
    pair<int, int> th = v[rt][i];

    if (dp[rt] > 0) dp[th.first] = dp[rt] + th.second;
    else dp[th.first] = th.second;

    if (dp[th.first] <= a[th.first]) {
      DP(th.first);
    } else {
      ans += c[th.first];
    }
  }
}


int main () {
  ios::sync_with_stdio(false);

  cin >> n;
  for (int i=1; i<=n; i++) {
    cin >> a[i];
  }

  int tmpa, tmpb;
  for (int i=2; i<=n; i++) {
    cin >> tmpa >> tmpb;
    v[tmpa].push_back(make_pair(i, tmpb));
  }

  ans = 0;

  CN(1);
  DP(1);

  cout << ans << endl;

  return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值