YBT高效进阶3.4.1 洛谷P3387有向图缩点

YBT高效进阶3.4.1 洛谷P3387有向图缩点

Title

思路

建图
Tanjan缩点
拓扑DP
设f[i]为以i为终点的值
f[v]=max(f[u]+s[v],f[v])
ans=max(f[i])

CODE

#include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
const long long maxn=200010;
struct jgt
{
	long long u,v,nxt;
} efirst[maxn],esd[maxn],edz[maxn];
long long a[maxn],dfn[maxn],low[maxn],col[maxn],s[maxn],ins[maxn],f[maxn],cnt,len;
long long headfirst[maxn],totfirst;
long long headsd[maxn],totsd;
long long headdz[maxn],totdz;
stack<long long>stck;
queue<long long>que;
void Tanjan(long long x)
{
	dfn[x]=low[x]=++cnt;
	stck.push(x);
	for(long long i=headfirst[x]; i; i=efirst[i].nxt)
		if(!dfn[efirst[i].v])Tanjan(efirst[i].v),low[x]=min(low[x],low[efirst[i].v]);
		else if(!col[efirst[i].v])low[x]=min(low[x],dfn[efirst[i].v]);
	if(dfn[x]==low[x])
	{
		for(col[x]=++len,s[len]=a[x]; stck.top()!=x; stck.top(),stck.pop())col[stck.top()]=len,s[len]+=a[stck.top()];
		stck.pop();
	}
	return;
}
int main()
{
	long long n,m,i,ans=0,j,w,x,y;
	ios::sync_with_stdio(false);
	for(cin>>n>>m,i=1; i<=n; i++)cin>>a[i];
	for(i=1; i<=m; i++)cin>>efirst[i].u>>efirst[i].v,efirst[i].nxt=headfirst[efirst[i].u],headfirst[efirst[i].u]=i;
	for(i=1; i<=n; i++)if(!dfn[i])Tanjan(i);
	for(i=1; i<=m; i++)
	{
		x=col[efirst[i].u],y=col[efirst[i].v];
		if(x!=y)
		{
			esd[++totsd].u=x,esd[totsd].v=y,esd[totsd].nxt=headsd[x],headsd[x]=totsd,ins[y]++;
			edz[++totdz].u=y,edz[totdz].v=x,edz[totdz].nxt=headdz[y],headdz[y]=totdz;
		}
	}
	for(j=1; j<=len; j++)
		if(!ins[j])
			que.push(j);
	for(; que.size(); que.pop())
	{
		for(w=que.front(),f[w]=s[w],j=headdz[w]; j; j=edz[j].nxt)
			f[w]=max(f[w],f[edz[j].v]+s[w]);
		for(j=headsd[w]; j; j=esd[j].nxt)
			if(!(--ins[esd[j].v]))que.push(esd[j].v);
		ans=max(ans,f[w]);
	}
	cout<<ans;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值