拓扑排序

本文介绍了一种使用C++实现图的拓扑排序的方法。通过定义顶点类vertex,并利用队列和向量等数据结构,实现了基于图的拓扑排序算法。该算法能够有效地对有向无环图进行排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<vector>
#include<list>
#include<queue>
#include<algorithm>
using namespace std;

class vertex{
    public:
        int  indegree;
        vector<vertex*> next;
        // List<int> adj;
        int topnum;
        int f;
        vertex():indegree(0),topnum(0){}

};

bool mycomp( const vertex & v1,const vertex &v2)
{
    if(v1.topnum!=v2.topnum)return v1.topnum<v2.topnum;
    else 
        return v1.topnum<v2.topnum;
}



int main()
{
    vector<vertex>graph;
    vector<vertex>out;
    vertex v1,v2,v3,v4,v5,v6,v7;
    v1.next.push_back(&v2);
    v2.indegree++;
    v1.next.push_back(&v3);
    v3.indegree++;
    v1.next.push_back(&v4);
    v4.indegree++;
    v2.next.push_back(&v4);
    v4.indegree++;
    v2.next.push_back(&v5);
    v5.indegree++;
    v3.next.push_back(&v6);
    v6.indegree++;
    v4.next.push__back(&v6);
    v6.indegree++;
    v5.next.push_back(&v4);
    v4.indegree++;
    v5.next.push_back(&v7);
    v7.indegree++;
    v7.next.push_back(&v6);
    v6.indegree++;
    v1.f=1;
    v2.f=2;
    v3.f=3;
    v4.f=4;
    v5.f=5;
    v6.f=6;
    v7.f=7;

    graph.push_back(v1);
    graph.push_back(v2);
    graph.push_back(v3);
    graph.push_back(v4);
    graph.push_back(v5);
    graph.push_back(v6);
    graph.push_back(v7);



    queue<vertex> q;
    int count=0;
    vector<vertex>::iterator it;
    for(it=graph.begin();it!=graph.end();it++)
    {
        if(it->indegree==0)
            q.push(*it);
    }
    while(q.size()!=0)
    {
        vertex v=q.front();
        q.pop();
        v.topnum=++count;
        out.push_back(v);

        vector<vertex*>::iterator it2;
        for(it2=v.next.begin();it2!=v.next.end();it2++)
            if((--((*it2)->indegree))==0) q.push(**it2);

    }
    sort(out.begin(),out.end(),mycomp);

    for(it=out.begin();it!=out.end();it++)
        cout<<"v"<<it->f<<endl;

    return 0;


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值