https://vjudge.net/contest/292999#problem/J
https://blog.csdn.net/V5ZSQ/article/details/64919651?locationNum=5&fps=1
Description
给出一棵有向树,有点权和边权,定义一个节点i的答案为以i为根的子树中有多少j的点权不小于j->i的简单路径上边权和,求所有点的答案
Input
第一行一整数T表示用例组数,每组用例首先输入树上点数n,之后n个整数x[i]表示第i个点的点权,最后n-1行每行三个整数u,v,w表示树上一条边u-v的边权是w,树根是1(1<=n<=5e5,1<=x[i],w<=1e9)
对于每个点,其贡献是对从自身开始往上一段连续的父亲节点每个点的答案加一,实时维护一个1~i的边权前缀和sum[j]以及对应的编号id[j],假设从根节点1到节点i有res个节点,那么所有sum[j]>=sum[res]-x[i]的j都是i能够贡献到的点,假设最小的满足条件的j是pos,pos可以对sum数组二分搜索得到,那么i节点的贡献就是在树上对id[pos],id[pos+1],…,i这条边每个节点的答案加一,类似前缀和优化,cnt[fa[id[pos]]]–,cnt[i]++,这样以来在往下深搜的时候把每个点的贡献记录下来,在回溯的时候将儿子节点的cnt累加到父亲节点上即得到所有点的答案
#include<cstdio> #include<algorithm> #include<cstring> using namespace std; const int maxm = 5e5 + 5; typedef long long ll; ll w[maxm], sum[maxm]; int pa[maxm], id[maxm], cnt[maxm]; int t; int n; struct edge { int v; ll w; edge(int v = 0, ll w = 0) : v(v), w(w) {}; }; vector<edge> ve[maxm]; int res; void dfs(int u, int p) { for(int i = 0; i < ve[u].size(); i++) { int v = ve[u][i].v; ll val = ve[u][i].w; if(v == p) continue; pa[v] = u; id[res] = v; sum[res] = sum[res - 1] + val; int pos = lower_bound(sum, sum + res + 1, sum[res] - w[v]) - sum; if(pos < res) cnt[u]++, cnt[pa[id[pos] ] ]--; res++; dfs(v, u); res--; cnt[u] += cnt[v]; } } int main() { freopen("car.in", "r", stdin); scanf("%d", &t); while(t--) { scanf("%d", &n); memset(pa, 0, sizeof(pa)); memset(sum, 0, sizeof(sum)); memset(cnt, 0, sizeof(cnt)); for(int i = 1; i <= n; i++) ve[i].clear(); int u, v; ll val; for(int i = 1; i <= n; i++) scanf("%lld", &w[i]); for(int i = 1; i < n; i++) { scanf("%d%d%lld", &u, &v, &val); ve[u].push_back(edge(v, val)); ve[v].push_back(edge(u, val)); } pa[1] = 0, id[0] = 1, sum[0] = 0; res = 1; dfs(1, 1); for(int i = 1; i <= n; i++) { printf("%d%c", cnt[i], i == n ? ' ' : ' '); } } return 0; }