帮帮忙,求强连通分量的tarjan算法,RE了,运行时错误,非常感谢
查看原帖
帮帮忙,求强连通分量的tarjan算法,RE了,运行时错误,非常感谢
1047440
fuzhoudawugui楼主2023/7/27 11:53
#include<iostream>
#include<stack>
using namespace std;

class Arc{
    public:
    Arc(int adj,Arc* nex){
        adjvex=adj;
        nextarc=nex;
    }
    int adjvex;
    Arc* nextarc;
};

class Node{
    public:
    Node(){
        firstarc=NULL;
    }
    Arc* firstarc;
};

class Graph{
    public:
    Node* nodearr;
    int vexnum;
    ~Graph(){
        delete[] nodearr;
        nodearr=NULL;
    }
};

void CreateGraph(Graph& G){
    int n; //点数
    int m; //边数
    cin>>n;
    cin>>m;
    G.vexnum=n;
    G.nodearr=new Node[n];
    int head;
    int tail;
    for(int i=0;i<m;i++){
        cin>>head;
        cin>>tail;
        Arc* next=G.nodearr[tail].firstarc;
        Arc* first=new Arc(head,next);
        G.nodearr[tail].firstarc=first;
    }
}

class Solution{
    public:
    Solution(Graph& graph):G(graph){
        dfn=new int[G.vexnum];
        low=new int[G.vexnum];
        for(int i=0;i<G.vexnum;i++){
            dfn[i]=0;
            low[i]=0;
        }
    }
    
    stack<int>s;
    int* dfn;
    int* low;
    int d=1;
    Graph G;
    
    int compare(int a,int b){
        return a > b ? b : a;
    }
    
    bool is_in(int i){
        stack<int> tmp=s;
        while(!tmp.empty()){
            if(tmp.top()==i){
                return true;
            }
            else{
                tmp.pop();
            }
        }
        return false;
    }
    
    void dfs(int vex){
        dfn[vex]=d;
        low[vex]=d;
        d++;
        s.push(vex);
        for(Arc* current=G.nodearr[vex].firstarc;current;current=current->nextarc){
            if(low[current->adjvex]==0){
            dfs(current->adjvex);
            low[vex]=compare(low[vex],low[current->adjvex]);
            }
            else if(is_in(current->adjvex)){
                low[vex]=compare(low[vex],low[current->adjvex]);
            }
        }
        if(dfn[vex]==low[vex]){
            while(!s.empty()){
                cout<<s.top()<<" ";
                if(s.top()==vex){
                    break;
                }
                s.pop();
            }
            cout<<endl;
        }
    }
    
    void solve(){
        dfs(0);
    }
    
    ~Solution(){
    delete[] dfn;
    delete[] low;
    dfn=NULL;
    low=NULL;
    }
};

int main(){
    Graph graph;
    CreateGraph(graph);
    Solution sol(graph);
    sol.solve();
    return 0;
}
2023/7/27 11:53
加载中...