题解:

一道不错的题目。

树DP可以求出从每个点出发的最长链,复杂度O(n)

然后就变成找一个数列里最长的连续区间使得最大值-最小值<=m了。

成了这题:http://www.cnblogs.com/zyfzyf/p/4008295.html

代码:

  1 #include<cstdio>
  2 
  3 #include<cstdlib>
  4 
  5 #include<cmath>
  6 
  7 #include<cstring>
  8 
  9 #include<algorithm>
 10 
 11 #include<iostream>
 12 
 13 #include<vector>
 14 
 15 #include<map>
 16 
 17 #include<set>
 18 
 19 #include<queue>
 20 
 21 #include<string>
 22 
 23 #define inf 1000000000
 24 
 25 #define maxn 1000000+5
 26 
 27 #define maxm 20000000+5
 28 
 29 #define eps 1e-10
 30 
 31 #define ll long long
 32 
 33 #define pa pair<int,int>
 34 
 35 #define for0(i,n) for(int i=0;i<=(n);i++)
 36 
 37 #define for1(i,n) for(int i=1;i<=(n);i++)
 38 
 39 #define for2(i,x,y) for(int i=(x);i<=(y);i++)
 40 
 41 #define for3(i,x,y) for(int i=(x);i>=(y);i--)
 42 #define for4(i,x) for(int i=head[x],y;i;i=e[i].next)
 43 
 44 #define mod 1000000007
 45 
 46 using namespace std;
 47 
 48 inline int read()
 49 
 50 {
 51 
 52     int x=0,f=1;char ch=getchar();
 53 
 54     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
 55 
 56     while(ch>='0'&&ch<='9'){x=10*x+ch-'0';ch=getchar();}
 57 
 58     return x*f;
 59 
 60 }
 61 struct edge{int go,next;ll w;}e[2*maxn];
 62 int n,tot,q[maxn][2],l[2],r[2],head[maxn];
 63 ll m,f[maxn],g[maxn][2],a[maxn];
 64 inline void insert(int x,int y,ll z)
 65 {
 66     e[++tot]=(edge){y,head[x],z};head[x]=tot;
 67 }
 68 inline void down(int x)
 69 {
 70     for4(i,x)
 71     {
 72         down(y=e[i].go);
 73         if(g[y][0]+e[i].w>g[x][0])g[x][1]=g[x][0],g[x][0]=g[y][0]+e[i].w;
 74         else g[x][1]=max(g[x][1],g[y][0]+e[i].w);
 75     }
 76 }
 77 inline void up(int x)
 78 {
 79     for4(i,x)
 80     {
 81         f[y=e[i].go]=f[x]+e[i].w;
 82         if(g[y][0]+e[i].w==g[x][0])f[y]=max(f[y],g[x][1]+e[i].w);
 83         else f[y]=max(f[y],g[x][0]+e[i].w);
 84         up(y);
 85     }
 86 }
 87 
 88 int main()
 89 
 90 {
 91 
 92     freopen("input.txt","r",stdin);
 93 
 94     freopen("output.txt","w",stdout);
 95 
 96     n=read();m=read();
 97     for2(i,2,n){int x=read(),y=read();insert(x,i,y);}
 98     down(1);up(1);
 99     for1(i,n)a[i]=max(f[i],g[i][0]);
100     l[0]=l[1]=1;r[0]=r[1]=0;
101     int ret=1,ans=0;
102     for1(i,n)
103     {
104        while(l[0]<=r[0]&&a[i]<=a[q[r[0]][0]])r[0]--;
105        q[++r[0]][0]=i;
106        while(l[1]<=r[1]&&a[i]>=a[q[r[1]][1]])r[1]--;
107        q[++r[1]][1]=i;
108        while(a[q[l[1]][1]]-a[q[l[0]][0]]>m)
109            ret=q[l[0]][0]<q[l[1]][1]?q[l[0]++][0]+1:q[l[1]++][1]+1;
110        ans=max(ans,i-ret+1);
111     }
112     cout<<ans<<endl;
113 
114     return 0;
115 
116 }  
View Code

相关文章:

  • 2021-11-24
  • 2021-05-26
  • 2021-09-09
  • 2022-01-24
  • 2021-06-29
  • 2022-02-27
  • 2021-07-18
  • 2021-12-03
猜你喜欢
  • 2021-12-13
  • 2021-06-07
  • 2022-03-09
  • 2021-10-15
  • 2021-06-10
  • 2021-10-28
  • 2022-03-01
相关资源
相似解决方案