cf 739B Alyona and a tree

一 原题

http://codeforces.com/contest/739/problem/B

二 分析

题意:给你一棵树,每个顶点和每条边都有一个权值。我们称点u控制点v,如果它们之间满足如下两个条件:1)v在以u为根节点的子树中,2)从u到v的简单路径上边的权重和dist(u, v)不超过v点的权重。顶点范围2e5,权值大小1-1e9

一个顶点s到它的各个祖先的距离是有序的,很容易想到可以二分找到最远能控制它的祖先t。找到后要做的事就是把从s的父亲到t路径上的点都ans++,直接操作是O(n)的。问题转换为在树上给定一条简单路径,如果高效的更新这条路径上所有的点。这是裸的树上差分操作。

三 代码

/*=====================================
*   
*   AUTHOR : maxkibble
*   CREATED: 2018.09.30 12:28:24
*
=====================================*/


#include <bits/stdc++.h>

using namespace std;

#define fi first
#define se second
#define pb push_back

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<int, long long> pil;
typedef pair<long long, int> pli;

const int maxn = 2e5 + 5;

int n;
int fa[maxn];
ll a[maxn];
vector<pil> t[maxn];
ll d[maxn];
vector<pli> tr;
int cnt[maxn];

void dfs1(int cur, int pre, ll len) {
  d[cur] = d[pre] + len;
  auto ptr = lower_bound(tr.begin(), tr.end(), make_pair(d[cur] - a[cur], 0));
  if (ptr != tr.end()) {
    // differential operation here
    cnt[fa[ptr->se]]--;
    cnt[tr[tr.size() - 1].se]++;
  }
  tr.pb({d[cur], cur});
  for (auto nxt: t[cur]) {
    if (nxt.fi == pre) continue;
    dfs1(nxt.fi, cur, nxt.se);
  }
  tr.pop_back();
}

void dfs2(int cur, int pre) {
  for (auto nxt: t[cur]) {
    if (nxt.fi == pre) continue;
    dfs2(nxt.fi, cur);
    cnt[cur] += cnt[nxt.fi];
  }
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0); cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  for (int i = 2; i <= n; i++) {
    int p;
    ll w;
    cin >> p >> w;
    fa[i] = p;
    t[i].pb({p, w});
    t[p].pb({i, w});
  }
  dfs1(1, 0, 0);
  dfs2(1, 0);
  for (int i = 1; i <= n; i++) cout << cnt[i] << " ";
  cout << endl;
  return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值