这两天看了byvoid大牛的tarjan算法讲解,后来自己又看了看书,那个byvoid大牛的代码中
if (v is not visted) // 如果节点v未被访问过
tarjan(v) // 继续向下找
Low[u] = min(Low[u], Low[v])
else if (v in S) // 如果节点v还在栈内
Low[u] = min(Low[u], DFN[v])
那个Low[u] = min(Low[u], Low[v]),Low[u] = min(Low[u], DFN[v])表示不是很理解,然后翻了翻书,发现书上的算法不需要记录instack这个bool数组,并且算法感觉比byvoid的算法更好理解。
下面上我的代码:
#define LIM 100 // LIM is the max number
int TIME; // the time of tarjan dfs visited sequence
int Group; // the group each strong connected
int low[LIM]; // record the min number which can go back
int dfn[LIM]; // record the time of tarjan dfs visited sequence
int belong[LIM]; // record the group each strong connected
stack<int> S; // save a stong connected stack
vector<int> G[LIM]; // graph
int n; // vertex number
void tarjan(int u){
int min,tmp;
min=dfn[u]=low[u]=TIME++;
S.push(u);
for( vector<int>::iterator it=G[u].begin() ; it!= G[u].end() ; it++ )
{
if( !dfn[*it] ) tarjan(*it);
if( min > low[*it] ) min= low[*it];
}
if( min < low[u] ){ low[u]=min; return; }
do{
tmp=S.top();
S.pop();
belong[tmp]=Group;
low[tmp]=n+1;
}while( tmp != u );
Group++;
}
void solve(){
TIME=Group=1;
memset(dfn,0,sizeof(dfn));
for(int i=1;i<=n;++i){
if( !dfn[i] ){
tarjan(i);
}
}
}
欢迎指正