hdu1269
题意
判断对于任意两点是否都可以互相到达(判断有向图强连通分量个数是否为 1 )。
分析
Tarjan 算法实现。
code
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int MAXN = 2e5 + 10;
int n, m;
struct Edge {
int to, next;
}e[MAXN];
int cnt, head[MAXN];
void addedge(int u, int v) {
e[cnt].to = v;
e[cnt].next = head[u];
head[u] = cnt++;
}
int sz, dfn[MAXN], low[MAXN], vis[MAXN];
int scc;
stack<int> sta;
void tarjan(int u) {
dfn[u] = low[u] = ++sz;
vis[u] = 1;
sta.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] > dfn[v]) {
low[u] = dfn[v];
}
}
if(low[u] == dfn[u]) {
scc++;
while(1) {
int id = sta.top(); sta.pop();
vis[id] = 0;
if(id == u) break;
}
}
}
int main() {
while(scanf("%d%d", &n, &m) && (n + m)) {
memset(vis, 0, sizeof vis);
while(!sta.empty()) sta.pop();
scc = cnt = sz = 0;
memset(head, -1, sizeof head);
memset(dfn, 0, sizeof dfn);
for(int i = 0; i < m; i++) {
int u, v;
scanf("%d%d", &u, &v);
addedge(u, v);
}
for(int i = 1; i <= n; i++) {
if(!dfn[i]) tarjan(i);
}
puts(scc == 1 ? "Yes" : "No");
}
return 0;
}