只过了 Hack 求条
查看原帖
只过了 Hack 求条
926886
kind_aunt楼主2024/11/22 11:50
#include<bits/stdc++.h>
#define int long long 
using namespace std;
const int N=1e4+5;
int n,m,a[N],in[N],u[N],v[N],vv;
vector<int> s[N];
vector<int> edge[N];
int dfn[N];//dfs 序
int low[N],squ[N];
bool vis[N];
int tt,uu;
stack<int> st;
void tarjan(int rt)
{
	vis[rt]=1;
	low[rt]=dfn[rt]=++tt;
	st.push(rt);
	for(auto i:s[rt])
	{
		vv=i;
		if(!dfn[vv])
		{
			tarjan(vv);
			low[rt]=min(low[rt],low[vv]);
		}
		else if(vis[vv]) low[rt]=min(low[rt],low[vv]);
	}
	if(low[rt]==dfn[rt])
	{
		while(st.size())
		{
			vv=st.top();
			st.pop();
			squ[vv]=rt;
			vis[vv]=0;
			if(vv==rt) break;
			a[rt]+=a[vv];
		}
	}
}
int dis[N],ans;
queue<int> q;
int toposort()
{
	for(int i=1;i<=n;i++)
	{
		if(squ[i]==i and !in[i])
			q.push(i),dis[i]=a[i];
	}
	while(q.size())
	{
		uu=q.front();
		q.pop();
		for(auto i:edge[uu])
		{
			vv=i;
			in[vv]--;
			dis[vv]=max(dis[vv],dis[uu]+a[vv]);
			if(!in[vv])
				q.push(vv);
		}
	}
	int maxn=-1;
	for(int i=1;i<=n;i++)
		maxn=max(maxn,dis[i]);
	return maxn;
}
signed main()
{
//	freopen("P3387_2.in","r",stdin);
//	freopen("P3387.out","w",stdout);
	cin>>n>>m;
	for(int i=1;i<=n;i++) cin>>a[i];
	for(int i=1;i<=m;i++)
	{
		cin>>u[i]>>v[i];
		s[u[i]].push_back(v[i]);
	}
	for(int i=1;i<=n;i++)
	{
		if(!dfn[i])
			tarjan(i);
	}
	for(int i=1;i<=m;i++)
	{
		uu=squ[u[i]],vv=squ[v[i]];
		if(uu==vv) continue;
		edge[uu].push_back(vv);
		in[vv]++;
	}
	ans=toposort();
	cout<<ans<<'\n';
	return 0;
}
2024/11/22 11:50
加载中...