【强连通分量】 HDOJ 1269 迷宫城堡

tarjan模板题。。。

#include <iostream>  
#include <queue>  
#include <stack>  
#include <map>  
#include <set>  
#include <bitset>  
#include <cstdio>  
#include <algorithm>  
#include <cstring>  
#include <climits>  
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 10005
#define maxm 100005
#define eps 1e-10
#define mod 1000000009
#define INF 99999999  
#define lowbit(x) (x&(-x))  
//#define lson o<<1, L, mid  
//#define rson o<<1 | 1, mid+1, R  
typedef long long LL;
//typedef int LL;
using namespace std;

int H[maxn], v[maxm], next[maxm];
int dfn[maxn], low[maxn], in[maxn];
int f[maxn], n, m, top;
stack<int> s;

void scanf(int &x)
{
	x = 0;
	char ch = getchar();
	while(ch == ' ' || ch == '\n') ch = getchar();
	while(ch >= '0' && ch <= '9') x = x*10+ch-'0', ch = getchar();
}
void read(void)
{
	int cnt = 0, a, b;
	while(m--) {
		//scanf("%d%d", &a, &b);
		scanf(a), scanf(b);
		next[cnt] = H[a], H[a] = cnt, v[cnt] = b, cnt++;
	}
}
void init(void)
{
	top = 0;
	memset(f, 0, sizeof f);
	memset(in, 0, sizeof in);
	memset(H, -1, sizeof H);
	memset(dfn, 0, sizeof dfn);
}
void tarjan(int u)
{
	low[u] = dfn[u] = ++top;
	s.push(u), in[u] = 1;
	for(int e = H[u]; ~e; e = next[e]) {
		if(!dfn[v[e]]) {
			tarjan(v[e]);
			low[u] = min(low[v[e]], low[u]);
		}
		else if(in[v[e]]) low[u] = min(dfn[v[e]], low[u]);
	}
	if(dfn[u] == low[u]) {
		int tmp = s.top();
		s.pop();
		in[tmp] = 0;
		while(tmp != u) {
			f[tmp] = u;
			tmp = s.top();
			s.pop();
			in[tmp] = 0;
		}
		f[tmp] = u;
	}
}
void work(void)
{
	for(int i = 1; i <= n; i++)
		if(!dfn[i]) tarjan(i);
	int ok = 1;
	for(int i = 2; i <= n; i++)
		if(f[i] != f[i-1]) {
			ok = 0;
			break;
		}
	if(ok) printf("Yes\n");
	else printf("No\n");
}
int main(void)
{
	while(scanf(n), scanf(m), n != 0 || m != 0) {
		init();
		read();
		work();
	}
	return 0;
}


你可能感兴趣的:(HDU)