题目大意:给一棵树,节点u可以控制节点v的条件是 dis(u,v)<=a[u](u为v的子节点),转换一下变成 depth[u]-depth[v]<=a[u],再变一下depth[u]-a[u]<=depth[v],然后dfs记录每个节点到根节点的边权值,因为前缀和满足单调性,所以从叶子节点二分查找边界点,找到对应边界点,边界点则减一(因为这时候对应的出发点不能被控制)。最后ans[rot]加上子节点最大能控制的就是它所能控制的最大点数。(因为前面已经减去它的子节点能控制而它本身刚好不能控制的点,二者相加抵消掉前者)。
pair可以用于lower_bound,如果想按只某个变量查找,make_pair的时候,对应变量的位置写为-1.并且搜索的时候只能是make_pair(ll,int)不能是(ll,ll)
代码:
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#define ll long long
using namespace std;
const int maxn=1e6+50;
ll n,a[maxn],fa,weight,ans[maxn],depth[maxn];///树上每个点到跟的边权的前缀和
vector<pair<ll,ll> >vec[maxn];///子节点和权值
vector<pair<ll,int> >path;///存储当前节点的每个祖先节点的边权前缀和
void dfs(int root){
path.push_back(make_pair(depth[root],root));
int it=lower_bound(path.begin(),path.end(),make_pair(depth[root]-a[root],-1))-path.begin()-1;///找到刚好满足的边界点
if(it>=0) ans[path[it].second]--;
for(int i=0;i<vec[root].size();i++){
int son=vec[root][i].first;
depth[son]=depth[root]+vec[root][i].second;
dfs(son);
ans[root]+=ans[son]+1;
}
path.pop_back();///这里记住要pop_back
}
int main(){
while(scanf("%lld",&n)!=EOF){
memset(a,0,sizeof(a));
memset(ans,0,sizeof(ans));
memset(vec,0,sizeof(vec));
memset(depth,0,sizeof(depth));
path.clear();
for(ll i=1;i<=n;i++)
scanf("%lld",&a[i]);
for(ll i=2;i<=n;i++){
scanf("%lld%lld",&fa,&weight);
vec[fa].push_back(make_pair(i,weight));
}
dfs(1);
for(int i=1;i<=n;i++)
printf("%lld%c",ans[i],i==n?'\n':' ');
}
return 0;
}