链接:https://ac.nowcoder.com/acm/problem/24367
来源:牛客网
题目描述
It's milking time at Farmer John's farm, but the cows have all run away! Farmer John needs to round them all up, and needs your help in the search.
FJ's farm is a series of N (1 <= N <= 200,000) pastures numbered 1...N connected by N - 1 bidirectional paths. The barn is located at pasture 1, and it is possible to reach any pasture from the barn. FJ's cows were in their pastures this morning, but who knows where they ran to by now.
FJ does know that the cows only run away from the barn, and they are too lazy to run a distance of more than L. For every pasture, FJ wants to know how many different pastures cows starting in that pasture could have ended up in.
输入描述:
* Line 1: 2 integers, N and L (1 <= N <= 200,000, 1 <= L <= 10^18) * Lines 2..N: The ith line contains two integers p_i and l_i. p_i (1 <= p_i < i) is the first pasture on the shortest path between pasture i and the barn, and l_i (1 <= l_i <= 10^12) is the length of that path.
输出描述:
* Lines 1..N: One number per line, the number on line i is the number pastures that can be reached from pasture i by taking roads that lead strictly farther away from the barn (pasture 1) whose total length does not exceed L.
示例1
输入
复制4 5 1 4 2 3 1 5
4 5 1 4 2 3 1 5
输出
复制3 2 1 1
3 2 1 1
说明
OUTPUT DETAILS: Cows from pasture 1 can hide at pastures 1, 2, and 4. Cows from pasture 2 can hide at pastures 2 and 3. Pasture 3 and 4 are as far from the barn as possible, and the cows can hide there.
备注:
64-bit integers (int64 in Pascal, long long in C/C++ and long in Java) are needed to store the distance values.
题意:给定一棵以1号结点为根的树,找出以每个结点为根的子树中距离1号结点的最短距离小于L的结点个数。
思路: dfs+可并堆(左偏树)
dfs遍历所有点,回溯时,用siz数组来存储距离<L的结点个数,用左偏树维护,当距离大于L时,将左偏树中的相应的边删掉,从而维护距离小于L。
代码:
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn=2e5+5;
typedef long long ll;
int e[maxn],nex[maxn],head[maxn],cnt;
int n,dis[maxn],siz[maxn],root[maxn],l[maxn],r[maxn];
ll L,len[maxn],v[maxn];
void add(int u,int v,ll w)
{
e[cnt]=v,len[cnt]=w,nex[cnt]=head[u],head[u]=cnt++;
}
int merge(int x,int y)
{
if(!x) return y;
if(!y) return x;
if(v[x]<v[y]) swap(x,y);
r[x]=merge(r[x],y);
if(dis[l[x]]<dis[r[x]]) swap(l[x],r[x]);
dis[x]=dis[r[x]]+1;
return x;
}
void dfs(int x)
{
siz[x]=1;
root[x]=x;
for(int i=head[x];~i;i=nex[i]){
v[e[i]]=v[x]+len[i];
dfs(e[i]);
siz[x]+=siz[e[i]];
root[x]=merge(root[x],root[e[i]]);
}
while(v[root[x]]-v[x]>L){
siz[x]--,root[x]=merge(l[root[x]],r[root[x]]);
}
}
int main()
{
memset(head,-1,sizeof head);
cin>>n>>L;
for(int i=2;i<=n;i++){
int u;ll w;
cin>>u>>w;
add(u,i,w);
}
dis[0]=-1;
dfs(1);
for(int i=1;i<=n;i++) cout<<siz[i]<<endl;
return 0;
}