题目:http://poj.org/problem?id=2186
今天学习了求有向图强连通子图的tarjan算法,思想实际上类似求无向图的割顶,因为同样用到了low函数,但割顶的low函数准则为对于非根节点u,如果存在孩子节点v使得low[v]>=low[u]则u为割顶;而强连通子图的low函数准则为对于节点u,如果所有尚未确定属于哪个SCC的子孙的low函数都不大于low[u],则u及其尚未确定属于哪个SCC的子孙同属一个SCC
#include <cstdio>
#include <vector>
#include <stack>
using namespace std;
#define MAX 10001
int N, M, dfsClock, pre[MAX], sccCnt, scc[MAX];
bool out[MAX];
vector<int> neighbour[MAX];
stack<int> st;
int dfs(int x)
{
int lowx, y, lowy;
const vector<int>& v = neighbour[x];
lowx = pre[x] = ++dfsClock;
st.push(x);
for(int i = 0, n = v.size(); i < n; ++i){
y = v[i];
if(!pre[y]){
lowy = dfs(y);
lowx = min(lowx, lowy);
}
else if(!scc[y]){
lowx = min(lowx, pre[y]);
}
}
if(lowx == pre[x]){
++sccCnt;
while(true){
y = st.top(); st.pop();
scc[y] = sccCnt;
// printf("scc[%d] = %d\n", y, scc[y]);
if(y == x) break;
}
}
return lowx;
}
void findScc()
{
memset(pre + 1, 0, N << 2);
memset(scc + 1, 0, N << 2);
dfsClock = sccCnt = 0;
for(int i = 1; i <= N; ++i){
if(!pre[i]) dfs(i);
}
}
void solve()
{
findScc();
memset(out + 1, false, N);
for(int i = 1; i <= N; ++i){
int ccno = scc[i];
const vector<int>& v = neighbour[i];
for(int j = 0, n = v.size(); j < n; ++j){
if(scc[v[j]] != ccno){
out[ccno] = true;
break;
}
}
}
int noout = 0;
for(int i = 1; i <= sccCnt; ++i){
if(!out[i]){
if(noout){
puts("0");
return;
}
else noout = i;
}
}
int cnt = 0;
for(int i = 1; i <= N; ++i){
if(scc[i] == noout) ++cnt;
}
printf("%d\n", cnt);
}
bool input()
{
if(2 != scanf("%d%d", &N, &M)) return false;
int i, x, y;
for(i = 1; i <= N; ++i) neighbour[i].clear();
for(i = 0; i < M; ++i){
scanf("%d%d", &x, &y);
neighbour[x].push_back(y);
}
return true;
}
int main()
{
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
while(input()) solve();
return 0;
}