tarjin模板题HDU1269

#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 10000 + 10;
const int maxm = 100000 + 10;
int head[maxn], pos, n, m; // 邻接表
int low[maxn], dfn[maxn], dfs_clock, sccon[maxn], cnt, instack[maxn];
int in[maxn], out[maxn];
stack  s;
struct edge
{
	int to;
	int next;
}Edge[maxm];
void addEdge(int u, int v){
	Edge[pos].to = v;
	Edge[pos].next = head[u];
	head[u] = pos;
	pos++;
}
void init(){

	// 初始化邻接表
	pos = 0;
	for(int i = 0; i < maxn; i++) head[i] = -1;

	// 初始化tarjin
	while(!s.empty()) s.pop();
	memset(dfn, 0, sizeof(dfn));
	memset(low, 0, sizeof(low));
	memset(instack, 0, sizeof(instack));
	memset(sccon, 0, sizeof(sccon));
	dfs_clock = 0;
	cnt = 0;

}
void tarjin(int u, int fa){
	dfn[u] = low[u] = ++dfs_clock;
	s.push(u);
	instack[u] = 1;
	for(int k = head[u]; k != -1; k = Edge[k].next){ // 递归搜索并计算该点的low值
		int v = Edge[k].to;
		if(!dfn[v]){
			tarjin(v, u);
			low[u] = min(low[u], low[v]);
		}else if(instack[v]){
			low[u] = min(low[u], dfn[v]);
		}
	}
	if(dfn[u] == low[u]){ // 当且仅当一个点的dfn == low时该点是强连通分量的dfs树树根
		cnt++;
		while(1){
			int v = s.top();
			s.pop();
			instack[v] = 0;
			sccon[v] = cnt;
			if(v == u) break;
		}
	}
}
void find(int l, int r){
	for(int i = l; i <= r; i++){ // 从一个没有被dfs过的点开始进行dfs,生成dfs树
		if(!dfn[i])
			tarjin(i, -1);
	}
}
void scc(){
	for(int i = 1; i <= cnt; i++){
		in[i] = 0;
		out[i] = 0;
	}
	for(int i = 1; i <= n; i++){
		for(int k = head[i]; k != -1; k = Edge[k].next){
			int v = sccon[Edge[k].to];
			int u = sccon[i];
			if(u != v){
				out[u]++;
				in[v]++;
			}
		}
	}
}
int main(){
	//freopen("input.txt", "r", stdin);
	while(scanf("%d%d", &n, &m) && n != 0){
		init();
		for(int i = 1; i <= m; i++){
			int u, v;
			scanf("%d%d", &u, &v);
			addEdge(u, v);
		}
		find(1, n);
		if(cnt == 1) printf("Yes\n");
		else printf("No\n");
	}
}
点击打开链接

你可能感兴趣的:(图论)