tarjan 40pts 求调
查看原帖
tarjan 40pts 求调
448884
快乐的大童楼主2023/1/9 21:19

RT

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<map>
#include<unordered_map>
#include<vector>
#include<queue>
#include<set>
#include<ctime>
#include<random>
#define x1 xx1
#define y1 yy1
#define IOS ios::sync_with_stdio(false)
#define ITIE cin.tie(0);
#define OTIE cout.tie(0);
#define PY puts("Yes")
#define PN puts("No")
#define popcount __builtin_popcount
using namespace std;
inline int R(){
	int x=0,f=1;char ch=getchar();
	while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
	while(isdigit(ch)){x=x*10+ch-48;ch=getchar();}return x*f;
}
inline void write(int x){
	if(x<0){x=-x;putchar('-');}
	int y=0;char z[70];
	while(x||!y){z[y++]=x%10+48;x/=10;}
	while(y--)putchar(z[y]);
}
inline void writesp(int x){
	write(x);putchar(32);
}
inline void writeln(int x){
	write(x);putchar(10);
}
#define rep(a,b,c) for(int a=b;a<=c;a++)
#define per(a,b,c) for(int a=b;a>=c;a--)
#define reprange(a,b,c,d) for(int a=b;a<=c;a+=d)
#define perrange(a,b,c,d) for(int a=b;a>=c;a-=d)
#define graph(i,j,k) for(int i=head[j];i;i=k[i].nxt)
const int maxn=1e4+5,maxm=1e5+5;
int n,m,w[maxn],ans;
struct edge{
	int to,nxt;
}a[maxm],e[maxm];
int head[maxn],cnt;
int hhead[maxn],ccnt;
void add(int x,int y){
	a[++cnt]=(edge){y,head[x]};
	head[x]=cnt;
}
void add1(int x,int y){
	e[++ccnt]=(edge){y,hhead[x]};
	hhead[x]=ccnt;
}
int dfn[maxn],low[maxn],dfncnt;
bool vis[maxn];
int scc[maxn],sc;
int sta[maxn],top;
void tarjan(int x){
	dfn[x]=low[x]=++dfncnt;
	sta[++top]=x,vis[x]=1;
	graph(i,x,a){
		int u=a[i].to;
		if(!dfn[u]){
			tarjan(u);
			low[x]=min(low[x],low[u]);
		}else if(vis[u]){
			low[x]=min(low[x],dfn[u]);
		}
	}
	if(dfn[x]==low[x]){
		++sc;
		while(sta[top]!=x){
			scc[sta[top]]=sc;
			vis[sta[top]]=0;
			top--;
		}
		scc[sta[top]]=sc;
		vis[sta[top]]=0;
		top--;
	}
}
queue<int>q;
int in[maxn];
int f[maxn],sum[maxn];
void topo(){
	rep(i,1,sc)
		if(!in[i]){
			q.push(i);
			f[i]=sum[i]; 
		}
	while(!q.empty()){
		int now=q.front();
		q.pop();
		graph(i,now,e){
			int u=e[i].to;
			in[u]--;
			if(!in[u]) q.push(u);
			f[u]=max(f[u],f[now]+sum[u]);
		}
	}
	rep(i,1,sc) ans=max(ans,f[i]);
}
int main(){
	n=R(),m=R();
	rep(i,1,n) w[i]=R();
	rep(i,1,m){
		int x=R(),y=R();
		add(x,y);
	}
	rep(i,1,n){
		if(!dfn[i]){
			tarjan(i);
		}
	}
	rep(i,1,n){
		graph(j,i,a){
			int u=a[j].to;
			if(scc[i]!=scc[u]){
				add1(scc[i],scc[u]);
				in[scc[u]]++;
			}
		}
	}
	rep(i,1,n) sum[scc[i]]+=w[i];
	topo();
	write(ans);
}

2023/1/9 21:19
加载中...