const int N = 1000009;
int dw1[N]; //向下最大
int dw2[N]; //向下次大
int up[N]; //向上最大
int m[2][N<<2]; //线段树的最值
int n, mm;
vector<pair<int, int> >v[N];
void dfs1(int s) //向下最大和向下次大
{
dw1[s] = dw2[s] = 0;
int i, ss, dd;
for(i=0; i<v[s].size(); i++)
{
ss = v[s][i].first;
dfs1(ss);
dd = v[s][i].second+dw1[ss];
if(dd >= dw1[s])
{
dw2[s] = dw1[s];
dw1[s] = dd;
}
else dw2[s] = max(dw2[s], dd);
}
}
void dfs2(int s, int pre, int len) //向上最大
{
int i, ss, dd;
if(dw1[pre]==dw1[s]+len) up[s] = len + max(up[pre], dw2[pre]);
else up[s] = len + max(up[pre], dw1[pre]);
for(i=0; i<v[s].size(); i++)
{
ss = v[s][i].first;
dd = v[s][i].second;
dfs2(ss, s, dd);
}
}
void build(int l, int r, int k)
{
if(l==r)
{
m[0][k] = m[1][k] = max(up[l], dw1[l]);
return;
}
int mid = (l+r)>>1, ls = k<<1, rs = k<<1|1;
build(l, mid, ls);
build(mid+1, r, rs);
m[0][k] = min(m[0][ls], m[0][rs]);
m[1][k] = max(m[1][ls], m[1][rs]);
}
int query(int ll, int rr, int l, int r, int k, int id)
{
if(ll==l && rr==r) return m[id][k];
int mid = (l+r)>>1, ls = k<<1, rs = k<<1|1;
if(rr<=mid) return query(ll, rr, l, mid, ls, id);
else if(ll>mid) return query(ll, rr, mid+1, r, rs, id);
else if(id==0) return min(query(ll, mid, l, mid, ls, id), query(mid+1, rr, mid+1, r, rs, id));
else return max(query(ll, mid, l, mid, ls, id), query(mid+1, rr, mid+1, r, rs, id));
}
int main()
{
int i, a, b;
while(~scanf("%d%d", &n, &mm))
{
for(i=1; i<=n; i++) v[i].clear();
for(i=2; i<=n; i++)
{
scanf("%d%d", &a, &b);
v[a].push_back( make_pair(i, b) );
}
dfs1(1);
dfs2(1, 0, 0);
build(1, n, 1);
int lft = 1, rit = 1, ans = 1;
while(rit<=n)
{
int t0 = query(lft, rit, 1, n, 1, 0);
int t1 = query(lft, rit, 1, n, 1, 1);
if(t1-t0<mm) {ans = max(ans, rit-lft+1); rit++;}
else lft++;
}
printf("%d\n", ans);
}
return 0;
}
POJ-3162-treeDP+线段树
最新推荐文章于 2019-10-09 16:28:12 发布