链接
题解
先考虑一条链上面怎么做,一条链肯定就是从尾端开始贪心的选
然后现在考虑两条链在某点相遇的时候怎么弄?
肯定要切断某条链上还没有连完的段,那我切断哪个,保留哪个呢?
很好想,保留那个更有潜力连出去较长的那个
那么其实切断那些之后,那些链其实就和这个问题无关了,只跟我保留的那个有关,那我我从下往上做这个问题,每次选择子树里面更有潜力连出去较长段的,被切断的直接统计到答案里去就行了,因为我只保留了一条链,所以其实就相当于我这一条链继续往上延伸,那么下次再参与决策的时候,其实本质上就是几条链在这一点汇聚的问题
代码
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define iinf 0x3f3f3f3f
#define linf (1ll<<60)
#define eps 1e-8
#define maxn 100010
#define maxe 200010
#define maxk 17
#define cl(x) memset(x,0,sizeof(x))
#define rep(_,__) for(_=1;_<=(__);_++)
#define em(x) emplace(x)
#define emb(x) emplace_back(x)
#define emf(x) emplace_front(x)
#define fi first
#define se second
#define de(x) cerr<<#x<<" = "<<x<<endl
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
ll read(ll x=0)
{
ll c, f(1);
for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-f;
for(;isdigit(c);c=getchar())x=x*10+c-0x30;
return f*x;
}
struct Graph
{
int etot, head[maxn], to[maxe], next[maxe], w[maxe];
void clear(int N)
{
for(int i=1;i<=N;i++)head[i]=0;
etot=0;
}
void adde(int a, int b, int c=0){to[++etot]=b;w[etot]=c;next[etot]=head[a];head[a]=etot;}
#define forp(_,__) for(auto p=__.head[_];p;p=__.next[p])
}G;
struct Doubling_LCA
{
int f[maxn][maxk+1], depth[maxn];
void clear(int n){for(int i=1;i<=n;i++)depth[i]=0, cl(f[i]);}
void dfs(Graph &G, int pos, int pre)
{
for(auto k=1;(1<<k)<=depth[pos];k++)f[pos][k]=f[f[pos][k-1]][k-1];
for(auto p(G.head[pos]);p;p=G.next[p])
if(G.to[p]!=pre)
{
f[G.to[p]][0]=pos;
depth[G.to[p]]=depth[pos]+1;
dfs(G,G.to[p],pos);
}
}
void run(Graph &G, int root)
{
depth[root]=1;
dfs(G,root,0);
}
int q(int x, int y)
{
if(depth[x]<depth[y])swap(x,y);
for(auto k(maxk);~k;k--)
if(depth[f[x][k]]>=depth[y])
x=f[x][k];
if(x==y)return x;
for(auto k(maxk);~k;k--)
if(f[x][k]!=f[y][k])
x=f[x][k], y=f[y][k];
return f[x][0];
}
int jp(int x, int b)
{
for(auto k=0;k<=maxk;k++)
if(b&(1<<k))x=f[x][k];
return x;
}
}db;
ll n, ans, res[maxn], w[maxn], f[maxn], S, L, s[maxn];
void dfs1(ll pos, ll pre)
{
s[pos]=s[pre]+w[pos];
forp(pos,G)dfs1(G.to[p],pos);
}
void dfs2(ll pos, ll pre)
{
ll mx=0, son=-1;
forp(pos,G)
{
dfs2(G.to[p],pos);
if(res[G.to[p]]>mx)
{
mx=res[G.to[p]];
son=G.to[p];
}
}
forp(pos,G)
if(G.to[p]!=son)ans++;
if(son==-1)
{
ll l=0, r=min(L-1,(ll)db.depth[pos]-1);
while(l<r)
{
ll mid=(l+r+1)>>1, to=db.jp(pos,mid);
if(s[pos]-s[db.f[to][0]]<=S)l=mid;
else r=mid-1;
}
res[pos]=l;
}
else
{
res[pos]=res[son]-1;
}
}
int main()
{
ll i;
n=read(), L=read(), S=read();
rep(i,n)w[i]=read();
rep(i,n)if(w[i]>S){cout<<-1;return 0;}
rep(i,n-1)
{
ll fa=read();
G.adde(fa,i+1);
}
db.run(G,1);
dfs1(1,0);
dfs2(1,0);
cout<<ans+1;
return 0;
}