大佬

珂朵莉喊你一声大佬

http://www.nowcoder.com/questionTerminal/ee47c7b4f07c4433ac660e262f250596

include

include

include

include

include

define LL long long

using namespace std;
const int N=1e6+77;
int n,m,f[N],F[N],a[N],cnt,b[N];
int head[N],nxt[2N],to[2N],tot;
int dfn[N],low[N],stack[N],color[N],top,dfs_num,color_num;
LL c[N],cc[N],num[N];
bool vis[N];
void add(int x,int y)
{
to[++tot]=y;
nxt[tot]=head[x];
head[x]=tot;
}
void dfs(int x)//拓扑排序
{
b[++cnt]=x;
for(int i=head[x];i;i=nxt[i])
dfs(to[i]);
}
void DFS(int x)//Tarjan缩点
{
dfn[x]=++dfs_num;
low[x]=dfs_num;
stack[++top]=x;
vis[x]=1;

for(int i=head[x];i;i=nxt[i])
{
    if(!dfn[to[i]])
    {
        DFS(to[i]);
        low[x]=min(low[x],low[to[i]]);
    }
    else
    if(vis[to[i]]) low[x]=min(low[x],dfn[to[i]]);
}

if(low[x]==dfn[x])
{
    vis[x]=0;
    color[x]=++color_num;

    while(stack[top]!=x)
    {
        vis[stack[top]]=0;
        color[stack[top]]=color_num;
        top--;
    }
    top--;
}

}
bool check(LL x)
{
for(int i=1;i<=color_num;i++) cc[i]=c[i];
LL last=m;

for(int i=cnt;i>=1;i--)
{
    int p=b[i],px=F[p];
    LL need=x*num[i];
    /*while(cc[p]<need&&px)
    {
        if(cc[px]>=need-cc[p])
        {
            cc[px]-=need-cc[p];
            cc[p]=need;
        }
        else
        {
            cc[p]+=cc[px];
            cc[px]=0;
        }
        px=F[px];
    }
    if(cc[p]<need)
    {
        if(last>=need-cc[p])
        {
            last-=need-cc[p];
            cc[p]=need;
        }
        else return 0;
    }
    if(cc[p]<need) return 0;*/
    if(need<=cc[p]) continue;
    if(!px) {
        if(last<need-cc[p]) return 0;
        else
        {
            last-=need-cc[p];
            cc[p]=need;
        }
    }
    if(cc[p]<need)
    {
        cc[px]-=need-cc[p];
        cc[p]=need;
    }
}
return 1;

}
int main()
{
//freopen("c2.in","r",stdin);
//freopen("c.out","w",stdout);
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d",&f[i]);
if(f[i]!=-1) add(f[i],i);
}
for(int i=1;i<=n;i++) scanf("%d",&a[i]);

for(int i=1;i<=n;i++) if(!dfn[i]) DFS(i);

memset(head,0,sizeof(head));
memset(to,0,sizeof(to));
memset(nxt,0,sizeof(nxt));
tot=0;

for(int i=1;i<=n;i++)
{
    if(color[i]!=color[f[i]])
    {
        add(color[f[i]],color[i]);
        F[color[i]]=color[f[i]];
    }//缩点
    num[color[i]]++;
    c[color[i]]+=a[i];
}

for(int i=1;i<=color_num;i++) if(!F[i]) dfs(i);//拓扑排序


LL L=0,R=2e9+7,mid,ans=L;
while(L<=R)
{
    mid=(L+R)>>1;
    if(check(mid)) ans=mid,L=mid+1;
    else R=mid-1;
}
printf("%lld\n",ans);
return 0;

}

全部评论

相关推荐

牛客717484937号:双飞硕没实习挺要命的
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务