强连通分量(Tarjan)

#include 
#include 

using namespace std;

const int maxn = 1001;

int map[maxn][maxn];
int V, E;

int visit[maxn];
int instack[maxn];
stack s;
int dfn[maxn];
int low[maxn];
int cnt;

void tarjan(int u){
    visit[u] = 1;
    instack[u] = 1;
    s.push(u);
    dfn[u] = low[u] = ++cnt;

    for(int v = 1; v <= V; ++v){
        if(map[u][v] == 1){
            if(!visit[v]){
                tarjan(v);
                low[u] = min(low[u], low[v]);
            }
            else if(instack[v]){
                low[u] = min(low[u], dfn[v]);
            }
        }
    };
    if(low[u] == dfn[u]){
        int m;
        do{
            m = s.top(); s.pop();
            instack[m] = 0;
            std::cout << m << ' ';
        }while(m != u);
        std::cout << "\n";
    }
}

void solve(){
    std::cin >> V >> E;
    for(int i = 1; i <= E; ++i){
        int v1, v2;
        std::cin >> v1 >> v2;
        map[v1][v2] = 1;
    }
    tarjan(1);
}

int main(){
    solve();
    return 0;
}

 

你可能感兴趣的:(图论)