[模板]tarjan算法求SCC
#include <iostream>
#include <cstdio>
#include <cstring>
#include <stack>
using namespace std;
struct Edge {
int to, next;
Edge(int _to = 0, int _next = 0) : to(_to), next(_next) {}
};
const int MAX_N = 1e4 + 7;
const int MAX_M = 1e5 + 7;
Edge e[MAX_M];
int dfn[MAX_N], low[MAX_N], head[MAX_N];
bool vis[MAX_N];
stack <int> st;
int cnt, order, mx;
void add(int a, int b) { e[++cnt].to = b; e[cnt].next = head[a]; head[a] = cnt; }
void tarjan(int u) {
dfn[u] = low[u] = ++order;
vis[u] = true;
st.push(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(vis[v]) {
low[u] = min(low[u], dfn[v]);
}
}
if(dfn[u] == low[u]) {
int num = 0, tmp;
do {
tmp = st.top();
st.pop();
vis[tmp] = false;
num++;
}while(tmp != u);
mx = max(mx, num);
}
}
int main() {
while(true) {
int n, m;
scanf("%d%d", &n, &m);
if(n == m && n == 0) break;
cnt = order = mx = 0;
for(int i = 1; i <= n; i++) dfn[i] = low[i] = head[i] = 0;
for(int i = 1; i <= m; i++) {
int a, b;
scanf("%d%d", &a, &b);
add(a, b);
}
tarjan(1);
if(mx == n) {
puts("Yes");
} else {
puts("No");
}
}
return 0;
}