迷宫城堡
分类:
Graph
1.题目描述
- 给你一个图,要你判断图是否为强连通图。
2.解题思路
- 根据Tarjan算法,直接去强连通缩点,最后判断点是否为1就好了。
3.AC代码
#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define maxn 10010
/* head */
struct Edge {
int to, next;
} E[maxn << 1];
int head[maxn], cnt;
int dfn[maxn], low[maxn], s[maxn], belong[maxn], sec, top, scnt;
bool inS[maxn];
void init() {
memset(head, -1, sizeof head);
memset(dfn, 0, sizeof dfn);
memset(low, 0, sizeof low);
cnt = scnt = sec = top = 0;
}
void addedge(int u, int v) {
E[cnt].to = v;
E[cnt].next = head[u];
head[u] = cnt++;
}
void tarjan(int u) {
dfn[u] = low[u] = ++sec;
inS[u] = 1;
s[top++] = u;
for (int i = head[u]; ~i; i = E[i].next) {
int v = E[i].to;
if (!dfn[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
} else if (inS[v] && low[u] > dfn[v]) low[u] = dfn[v];
}
if (dfn[u] == low[u]) {
++scnt;
int tmp;
do {
tmp = s[--top];
inS[tmp] = 0;
belong[tmp] = scnt;
} while (tmp != u);
}
}
int main() {
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
long _begin_time = clock();
#endif
int n, m;
while (~scanf("%d%d", &n, &m) && m + n) {
init();
while (m--) {
int u, v;
scanf("%d%d", &u, &v);
addedge(u, v);
}
rep(i, 1, n + 1) {
if (!dfn[i]) tarjan(i);
}
puts(scnt == 1 ? "Yes" : "No");
}
return 0;
}