90 WA on #7 求调
查看原帖
90 WA on #7 求调
450705
__phiu楼主2023/3/20 18:49

rt

#include<iostream>
#include<queue>
using namespace std;
struct edge{
    int to;
    int nex;
    int from;
}e[500000],ed[500000];
int head[500000];
int dfn[500000];
int low[500000];
int n,m;
int tot;
int now;
void add(int x,int y)
{
    
    e[++tot].to=y;
    e[tot].nex=x;
    e[tot].from=head[x];
    head[x]=tot;
    return;
}
int stack[500000];
int top;
int in[500000];
int p[500000];
int cnt;
bool vis[500000];
void tarjan(int x,int fa)
{
    stack[++top]=x;
    vis[x]=1;
    dfn[x]=low[x]=++now;
    for(int i=head[x];i;i=e[i].from)
    {
        int to=e[i].to;
        if(!dfn[to])
        {
            tarjan(to,x);
            low[x]=min(low[x],low[to]);
        }
        else if(vis[to])
            low[x]=min(low[x],dfn[to]);
    }
    if(dfn[x]==low[x])
    {
        while(stack[top]!=x)
        {
            int y=stack[top--];
            in[y]=x;
            vis[y]=0;
            p[x]+=p[y];
        }
        top--;
        in[x]=x;
        vis[x]=0;
    }
}
int r[500000];
void make()
{
    for(int i=1;i<=m;i++)
	{
	    if(in[e[i].nex]!=in[e[i].to])
	    {
	        ed[++cnt].nex=in[e[i].nex];
	        ed[cnt].from=head[in[e[i].nex]];
	        ed[cnt].to=in[e[i].to];
	        head[in[e[i].nex]]=cnt;
	        r[in[e[i].to]]++;
	    }
	}
}
void init()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        cin>>p[i];
    for(int i=1;i<=m;i++)
    {
        int x,y;
        cin>>x>>y;
        add(x,y);
    }
}
void topo()
{
    int dist[500000];
    queue<int>q;
	for(int i=1;i<=n;i++)
	    if(in[i]==i&&!r[i])
	    {
	    	q.push(i);
            dist[i]=p[i];
	    } 
	while (!q.empty())
	{
		int k=q.front();
		q.pop();
		for (int i=head[k];i;i=ed[i].from)
		{
			int v=ed[i].to;
			dist[v]=max(dist[v],dist[k]+p[v]);
			r[v]--;
			if(r[v]==0) 
			    q.push(v);
		}
	}
    int ans=0;
    for (int i=1;i<=n;i++)
    ans=max(ans,dist[i]);
    cout<<ans;
}
int main(){
    init();
    for(int i=1;i<=n;i++)
    {
        if(!dfn[i])
            tarjan(i,i);
    }
	make();
	topo();
}
2023/3/20 18:49
加载中...