#include<iostream>//强连通分量tarjan
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
#define maxn 400010
#define INF 1e18
int low[maxn],dfn[maxn],sta[maxn],d[maxn]/*value*/,dis[maxn]/*total value*/,fa[maxn];/*enumerate*/
int ne[maxn],u[maxn],v[maxn],fi[maxn];
int f[maxn];
bool omit[maxn];
int n,m,t,top,times,tot;
int ans;
void edge(int x,int y)
{
t++;
ne[t]=fi[x];
fi[x]=t;
u[t]=x;
v[t]=y;
}
void scc(int now)//strongly connectly component
{
times++;
dfn[now]=low[now]=times;
top++;
sta[top]=now;
omit[now]=0;
for (int i=fi[now];i!=-1;i=ne[i])
{
if (!dfn[v[i]])
{
scc(v[i]);
low[now]=min(low[now],low[v[i]]);
}
else if (!omit[v[i]])
{
if (dfn[v[i]]<low[now]) low[now]=dfn[v[i]];
}
}
if (low[now]==dfn[now])
{
tot++;
do
{
dis[tot]+=d[sta[top]];
fa[sta[top]]=tot;
omit[sta[top]]=1;
top--;
}
while (sta[top+1]!=now);
}
}
int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++) scanf("%d",&d[i]);
t=-1;
top=0;
tot=0;
times=0;
memset(dis,0,sizeof(dis));
memset(dfn,0,sizeof(dfn));
memset(num,0,sizeof(num));
for (int i=1;i<=n;i++) fi[i]=-1;
for (int i=1;i<=m;i++)
{
int x,y;
scanf("%d%d",&x,&y);
edge(x,y);
}
for (int i=1;i<=n;i++)
if (!dfn[i]) scc(i);
return 0;
}
原文地址:https://www.cnblogs.com/reshuffle/p/12563244.html
时间: 2024-10-12 18:41:32