拓扑排序 C++代码实现

#include <iostream>
using namespace std;
#define MAX 10000000
#define MAX_VERTEX_NUM 20
/*顺序栈的定义*/
#define Stack_Size 100
typedef struct sqStack
{
       int *elem;
       int top;
       int stackSize;//栈数组长度
}sqStack;


/*顺序栈的初始化*/
void initStack_Sq(sqStack &S)
{
       S.elem=new int[Stack_Size];
       S.top=-1;
       S.stackSize=Stack_Size;
}
/*入栈*/
void push(sqStack &S,int x)
{
       if(S.top==Stack_Size-1)
              cout<<"Stack Overflow!";
       S.elem[++S.top]=x;
}

/*出栈*/
int pop(sqStack &S)
{
       int x;
       if(S.top==-1)
              cout<<"Stack Empty!";
       x=S.elem[S.top--];
       return x;
}
typedef struct EdgeNode
{//边表结点的定义
    int adjvex;//存放邻接点在顶点表中的位置
    struct EdgeNode * nextedge;//指向下一个边表结点
}EdgeNode;
typedef struct VexNode
{//顶点表结点的定义
    char vex;//存放顶点信息
    EdgeNode * firstedge;//指向第一个边表结点
    int indegree;
}VexNode;
typedef struct
{//顶点表的定义
    VexNode vexs[MAX_VERTEX_NUM];
    int vexnum,edgenum;
}LGraph;
/*构造有向图的邻接表*/
void CreateDG_AL(LGraph &G,int n,int e)
{
    int i,j,k;
    G.vexnum=n;
    G.edgenum=e;
    for(i=0;i<n;i++)
    {
        cin>>G.vexs[i].vex;
        G.vexs[i].firstedge=NULL;//初始化为空
    }
    for(k=0;k<e;k++)
    {
        EdgeNode *p;
        cin>>i>>j;
        p=new EdgeNode;
        p->adjvex=j;
        p->nextedge=G.vexs[i].firstedge;
        G.vexs[i].firstedge=p;//采用头插法
    }
}
//拓扑排序
void TopoSort(LGraph &G)
{
    sqStack S;
    initStack_Sq(S);
    EdgeNode *p;
    int count=0;
    int i,j;
    for(i=0;i<G.vexnum;i++)
        G.vexs[i].indegree=0;//初始化为0
    for(i=0;i<G.vexnum;i++)
    {//计算各个顶点的入度
        p=G.vexs[i].firstedge;
        while(p)
        {
            G.vexs[p->adjvex].indegree++;
            p=p->nextedge;
        }
    }
    for(i=0;i<G.vexnum;i++)
        if(G.vexs[i].indegree==0)
            push(S,i);//将度为0的顶点入栈,这里进栈的是入度为0的顶点在数组中的位置
    while(S.top!=-1)
    {
        j=pop(S);
        cout<<G.vexs[j].vex<<" ";//将栈顶的元素出栈且输出,即将入度为0的顶点输出
        count++;//计数器加1
        p=G.vexs[j].firstedge;//让p指向入度为0的顶点的第一个边表结点
        while(p)
        {
            G.vexs[p->adjvex].indegree--;//将入度为0的顶点的邻接点的入度减1
            if(G.vexs[p->adjvex].indegree==0)
                push(S,p->adjvex);//度减1后的顶点如果其入度为0,则将其入栈
            p=p->nextedge;
        }
    }
    if(count<G.vexnum)
        cout<<"Network G has citcuits!"<<endl;
}
void main()
{
    freopen("in.txt","r",stdin);
    LGraph G;
    CreateDG_AL(G,6,9);
    TopoSort(G);
}

在大一做实验课的时候,就看到实验室的墙上贴着很多图片,当时我很好奇的看那些图,可是就是看不懂,但我很深刻的记住了那是什么图,就是拓扑结构图,当时我就想,拓扑,好神奇的一个名字啊,肯定有深奥的知识在里面,感觉这个东西很神圣一样。现在我不仅懂了什么是拓扑,而且还可以自己把它的代码写出来,有了一点点的成就感,而更多的是我知道了一个一直在我心里却不知道它是一个什么东西的东西,呵呵,我挺开心的。虽然我知道拓扑的应用很广,我现在掌握的也只是它的表面,但由于现在我没有那么多时间去深研究它,但我以后再用到它的时候,我一定会好好研究一下它,现在还有很多的基础知识我没有掌握。数据结构我的感觉是越往后越复杂,越不容易理解,我得花很多时间在还没有懂的东西上,我得把他们都搞懂,然后再去一一深究他们!

 

“哎呦,代码谁教你的啊?”

“哎呦!我生下来就会啊,你不知道啊?”

“哎呦,PI 啊!”

 

  • 8
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
C++中的拓扑排序通常用于有向无环图(DAG, Directed Acyclic Graph)中,它将图中所有的节点按照它们的依赖关系排成线性的顺序。这种排序可以帮助我们确定任务的执行顺序,例如在一个任务图中,先完成的任务可以放在前面。 下面是一个简单的C++代码实现,使用邻接表来表示图,并使用深度优先搜索(DFS)进行排序: ```cpp #include <iostream> #include <vector> #include <list> using namespace std; // 图节点结构体 struct Node { int id; vector<int> adj; // 存储邻居节点 }; // 检查图是否强连通分量 bool isCyclic(Node* node, list<Node*> &visited, list<Node*>& result) { visited.push_back(node); bool hasCycle = false; for (int neighbor : node->adj) { if (visited.end() == find(visited.begin(), visited.end(), static_cast<Node*>(neighbor))) { hasCycle |= isCyclic(neighbor, visited, result); } } if (!hasCycle) { result.push_back(node); return false; } else { visited.pop_back(); return true; } } // 拓扑排序 void topologicalSort(vector<Node>& graph) { int n = graph.size(); list<Node*> nodes(n), result; // 初始化所有节点为未访问状态 for (int i = 0; i < n; ++i) nodes[i] = &graph[i]; // 对每个节点,如果发现没有从它指向的边,将其加入结果列表 for (Node* node : nodes) { if (isCyclic(node, list<Node*>(), result)) { // 如果存在环,则无法排序 cout << "Graph contains a cycle and is not a DAG." << endl; return; } } // 将节点按顺序添加到结果列表 while (!result.empty()) { Node* current = result.front(); result.pop_front(); cout << current->id << " "; for (int neighbor : current->adj) nodes.erase(find(nodes.begin(), nodes.end(), static_cast<Node*>(neighbor))); } } // 示例图构造 void buildExampleGraph(vector<Node>& graph) { Node node1{1, {2}}; Node node2{2, {3}}; Node node3{3, {}}; graph.push_back(node1); graph.push_back(node2); graph.push_back(node3); } int main() { vector<Node> graph; buildExampleGraph(graph); // 假设这里构造了一个示例图 cout << "Topological sort of the example graph: "; topologicalSort(graph); cout << endl; return 0; } ```
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值