tarjan algorithm - the largest connected component (template)

int Stack[maxn], low[maxn], dfn[maxn], inStack[maxn], belong[maxn];
int now,  cnt; // now:时间戳,cnt强连通的个数
vector<int> g[maxn];
stack<int> s;
void init() {
    now = cnt = 0;
    memset(inStack, 0,sizeof(inStack));
    memset(belong, 0,sizeof(belong));
    memset(dfn, 0,sizeof(dfn));
    memset(low, 0,sizeof(low));
    for(int i=0;i<maxn;i++) g[i].clear();
}
void tarjan(int u) {
    // 打上标记,入栈
    low[u] = dfn[u] = ++now;
    s.push(u);
    inStack[u] = 1;
    for (int i = 0; i < (int)g[u].size(); ++i) {
        int v = g[u][i];
        if (!dfn[v]) { //未访问过 
            tarjan(v);
            low[u] = min(low[u], low[v]); //low, dfn (v) it may be the smallest 
        }
         the else  IF (inStack [V]) { // visited, the stack is still 
            Low [U] = min (Low [U], DFN [V]); // dfn (v) to find the minimum 
           } 
    } 
    // back, if the current node dfn = low stack represents a strongly connected components form 
    IF (DFN [U] == Low [U]) {
         ++ CNT; // count a number 
        int Top;
         the while (! s.top () = U) { 
            Top = s.top (); 
            s.pop (); 
            belong [Top] = CNT; 
            inStack [Top] = 0 ;
        }
        Top = s.top (); 
        belong [Top] = CNT; // affiliation of each recording point 
       s.pop (); 
    } 
} 
for ( int I = . 1 ; I <= n-; I ++) { // a Tarjan may not be placed on every point, 
    IF (! Tarjan (I) DFN [I]); 
}

 

Guess you like

Origin www.cnblogs.com/jjl0229/p/11305068.html