跳到正文

个人记录

P3387 【模板】缩点

Splay_trees约 6 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 6 分钟

版本

  1. v1当前

link

0x80 前置知识

图论基础;拓扑排序;Tarjan 算法(割点割边);SCC

0x00 缩点

在一些有向图的不可重贡献问题上,我们常常将这个有向图的所有 SCC 在一张新图里用一个大点表示。可以证明,这个新图是一个 DAG,我们就可以用拓扑排序等在这个简单的新图上解决问题。

缩点的本质是求出 SCC 的过程。这里先只讲 Tarjan,因为它普适性更强,而且我不会 Kosaraju

0x01 求 SCC

鉴于读者已经知道 Tarjan 怎么求割点割边,我就直接摆结论了:

首先,在 Tarjan 求 SCC 的时候不需要判反向边,因为这是有向图。

其次,在 Tarjan 求 SCC 的时候,是在最后遍历完所有点之后,判断 low[u]==dfn[u]low[u]==dfn[u] ,因为这代表以 uu 为根的搜索子树之中的所有点,向上返祖最多只能回到 uu ,所以 uu 就是强连通分量的第一个节点。

实现的时候我们用一个栈。这个栈类似于搜索栈,不过在 return 的时候不退栈。这样,当我们发现一个 SCC 的起点 uu 的时候,把 toptop 一直到 uu 的节点一次性打上颜色(标记 SCC 序号),就求出了以 uu 为根搜索子树构成的 SCC 。

0x02 建图

建图暴力建就好,先累加每个点的点权,然后对于原图的每一个点,把它对应的 SCC 编号和它所有出边的达点的 SCC 编号相连(当然同一个就不连)即可。

0x03 拓扑排序

直接在新图上拓扑排序即可。最后求出 dis 的最大值就是答案。

AC Code:

C++
#include <iostream>
#include <cstring>
#define N ((int)1e4+5)
using namespace std;
int n,m,w[N];

namespace orig
{
	int head[N],cnt;
	struct edge
	{
		int to,nxt;
	} e[N*10];

	void add_edge(int u,int v)
	{
		e[++cnt].to=v,e[cnt].nxt=head[u],head[u]=cnt;
	}
};

namespace dag
{
	int head[N],cnt;
	struct edge
	{
		int to,nxt;
	} e[N*10];
	void add_edge(int u,int v)
	{
		e[++cnt].to=v,e[cnt].nxt=head[u],head[u]=cnt;
	}
};

int dfn[N],low[N],color[N],w2[N],p,scccnt;
int stk[N],top;
bool in[N];
void tarjan(int x)
{
	using namespace orig;
	dfn[x]=low[x]=++p;
	in[x]=1;
	stk[++top]=x;
	for(int i=head[x];~i;i=e[i].nxt)
	{
		if(!dfn[e[i].to])
		{
			tarjan(e[i].to);
			low[x]=min(low[x],low[e[i].to]);
		}
		else if(in[e[i].to])
		{
			low[x]=min(low[x],dfn[e[i].to]);
		}
	}
	if(dfn[x]==low[x])
	{
		++scccnt;
//		cout<<"Found SCC #"<<scccnt<<endl;
		while(stk[top+1]!=x)
		{
			color[stk[top]]=scccnt;
			w2[scccnt]+=w[stk[top]];
			in[stk[top]]=0;
//			cout<<stk[top]<<' ';
			--top;
		}
//		cout<<endl;
	}
	return;
}

int indag[N];
void build_dag()
{
	using namespace orig;
	for(int x=1;x<=n;x++)
	{
		for(int i=head[x];~i;i=e[i].nxt)
		{
			if(color[e[i].to]==color[x])
				continue;
			dag::add_edge(color[x],color[e[i].to]);
			++indag[color[e[i].to]];
		}
	}
}

#include <queue>
int dis[N];
void topu()
{
	using namespace dag;
	queue<pair<int,int> > q;
	for(int i=1;i<=scccnt;i++)
		dis[i]=w2[i];
	for(int i=1;i<=scccnt;i++)
		if(indag[i]==0)
			q.push(make_pair(i,w2[i]));
	while(!q.empty())
	{
		auto k=q.front();
		q.pop();
		int u=k.first,d=k.second;
		for(int i=head[u];~i;i=e[i].nxt)
		{
			dis[e[i].to]=max(dis[e[i].to],d+w2[e[i].to]);
			--indag[e[i].to];
			if(indag[e[i].to]==0)
				q.push(make_pair(e[i].to,dis[e[i].to]));
		}
	}
}

int main()
{
	using namespace orig;
	memset(head,-1,sizeof(head));
	memset(dag::head,-1,sizeof(dag::head));
	cin>>n>>m;
	for(int i=1;i<=n;i++)
		cin>>w[i];
	for(int i=1;i<=m;i++)
	{
		int x,y;
		cin>>x>>y;
		add_edge(x,y);
	}
	for(int i=1;i<=n;i++)
		if(!dfn[i])
			tarjan(i);
	build_dag();
	topu();
	int ans=-1;
	for(int i=1;i<=scccnt;i++)
		ans=max(ans,dis[i]);
	cout<<ans<<endl;
	return 0;
}
原文