Tarjian模板

2017/11/05 OI 图论

Tarjian模板

  既然是模板,就没什么好说的。

/**
 * tarjian 模板
 * 参见:https://www.byvoid.com/zhs/blog/scc-tarjan
*/
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>

using namespace std;

vector<vector<int> > graph;
vector<int> dfn;
vector<int> low;
vector<bool> if_in_stack;
stack<int> Stack;
vector<int> ans;
int ans_cot=0;
int time_cot=0;
int n,m;

void tarjian(int now)
{
	dfn[now]=time_cot++;
	low[now]=dfn[now];
	if_in_stack[now]=true;
	Stack.push(now);
	for(int i=0;i<graph[now].size();i++)
	{
		int to=graph[now][i];
		if(!dfn[to])
		{
			tarjian(to);
			low[now]=min(low[now],low[to]);
		}
		else if(if_in_stack[to]&&dfn[to]<low[now])
			low[now]=dfn[to];
	}
	if(low[now]==dfn[now])
	{
		int to=-1;
		ans_cot+=1;
		do{
			to=Stack.top();
			Stack.pop();
			if_in_stack[to]=false;
			ans[to]=ans_cot;
		}while(now!=to);
	}
}

int main()
{
	cin>>n>>m;
	dfn.resize(n,0);
	low.resize(n,0);
	ans.resize(n,-1);
	if_in_stack.resize(n,false);
	graph.resize(n);
	for(int i=0;i<m;i++)
	{
		int start,to;
		cin>>start>>to;
		start-=1;
		to-=1;
		graph[start].push_back(to);
	}
	for(int i=0;i<n;i++)
	{
		if(!dfn[i])
			tarjian(i);
	}
	for(int i=0;i<n;i++)		//print ans
		cout<<ans[i]<<endl;
	return 0;
}
Show Disqus Comments

Search

    welcome to visit my github

    creatorlxd's github

    Table of Contents