poj3162

这题卡常数了,nlogn链式前向星过了,用vector的O(n)没过。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cstring>
#include <map>
#include <queue>
#include <set>
#include <cassert>
#include <stack>
#include <bitset>
#define mkp make_pair
using namespace std;
const double EPS=1e-12;
typedef long long lon;
const lon SZ=1000010,SSZ=2*SZ,APB=26,one=1;
const lon INF=0x7FFFFFFF,mod=1000000007;
int n,m,dp[SZ][5],ans[SZ],cnt;
int head[SZ],nex[SSZ],to[SSZ],wt[SSZ];

void add(int u,int v,int w)
{
    ++cnt;
    nex[cnt]=head[u];
    head[u]=cnt;
    to[cnt]=v,wt[cnt]=w;
}

void init()
{
    cin>>n>>m;
    memset(head,-1,sizeof(head));
    for(int i=2;i<=n;++i)
    {
        int a,b;
        //cin>>a>>b;
        scanf("%d%d",&a,&b);
        add(a,i,b);
        add(i,a,b);
    }
}

void dfs1(int x,int p)
{
    for(int i=head[x];i!=-1;i=nex[i])
    {
        int t=to[i];
        int w=wt[i];
        if(t!=p)
        {
            dfs1(t,x);
            if(dp[t][0]+w>dp[x][0])
            {
                dp[x][1]=dp[x][0];
                dp[x][0]=dp[t][0]+w;
                dp[x][2]=t;
            }
            else
            {
                dp[x][1]=max(dp[x][1],dp[t][0]+w);
            }
        }
    }
}

void dfs2(int x,int p)
{
    for(int i=head[x];i!=-1;i=nex[i])
    {
        int t=to[i];
        int w=wt[i];
        if(t!=p)
        {
            if(t!=dp[x][2])dp[t][3]=max(dp[x][3],dp[x][0])+w;
            else dp[t][3]=max(dp[x][3],dp[x][1])+w;
            dfs2(t,x);
        }
    }
}

void work()
{
    dfs1(1,-1);
    dfs2(1,-1);
    for(int i=1;i<=n;++i)
    {
        ans[i]=max(dp[i][0],dp[i][3]);
        //cout<<" "<<dp[i][1]<<endl;
    }
    int ll=1,rr=1;
    multiset<int> st;
    st.insert(ans[1]);
    int res=1;
    int maxv=*--st.end(),minv=*st.begin();
    for(;rr<=n;)
    {
        ++rr;
        if(rr>n)break;
        st.insert(ans[rr]);
        maxv=*--st.end(),minv=*st.begin();
        if(maxv-minv<=m)res=max(res,rr-ll+1);
        
        for(;maxv-minv>m;)
        {
            st.erase(st.find(ans[ll]));
            ++ll;
            maxv=*--st.end(),minv=*st.begin();
        }
        maxv=*--st.end(),minv=*st.begin();
        if(maxv-minv<=m)res=max(res,rr-ll+1);
    }
    cout<<res<<endl;
}

void release()
{
    
}

int main()
{
    //std::ios::sync_with_stdio(0);
    //freopen("d:\\1.txt","r",stdin);
    int casenum;
    //cin>>casenum;
    //cout<<casenum<<endl;
    //for(int time=1;time<=casenum;++time)
    //for(int time=1;cin>>n>>m;++time)
    {
        init();
        work();
        release();
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/gaudar/p/10765054.html