uva6195

题目链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4206
此题就是求拓扑排序的个数 图没有拓扑排序则输出0 只有一种拓扑排序则输出1 有2种及以上的拓扑排序则输出2
下面是代码

// topsort.cpp : Defines the entry point for the console application.
//


#include <iostream>
#include <cstdlib>
#include <queue>
using namespace std;
#define MAXNUM 1000
typedef struct edge
{
    int argv;
    struct edge *next;
}Edge;
typedef struct vertex
{
    int rudu;
    struct edge *first;
}Vertex;
typedef struct graph
{
    Vertex v[MAXNUM];
    int n;
    int m;
}Graph;
int main(int argc, char **argv)
{
    Graph g;
    queue<int> q;
    int n1, m1,s,e,output,queuenum;
    struct edge *temp;
    cin >> n1;
    cin >> m1;
    while (n1 != 0 || m1 != 0)
    {
        g.n = n1;
        g.m = m1;
        output = 1;//默认输出为1  当图没有拓扑排序的时候为0 只有一个拓扑排序为1 有超过1个拓扑排序为2
        queuenum = 0;//从队列中输出的顶点的个数
        for (int i = 1; i <= g.n; i++)//将图的n个顶点进行初始化
        {
            g.v[i].first = NULL;
            g.v[i].rudu = 0;
        }
        for (int i = 0; i < g.m; i++)//读入m条边
        {
            cin >> s;//输入边起点
            cin >> e;//输入边终点
            temp = new edge;
            temp->argv = e;
            temp->next = g.v[s].first;
            g.v[s].first = temp;
            g.v[e].rudu++;//终点入度增加1


        }
        for (int i = 1; i <= g.n; i++)//找到所有入度为0的顶点 将其压入队列之中
        {
            if (g.v[i].rudu == 0)
                q.push(i);
        }
        while (!q.empty())
        {
            if (q.size() > 1)//只要队列中有同时存在不止一个入度为0 的元素则说明拓扑排序的顺序不止一个 修改输出为2
                output = 2;
            int tmp = q.front();
            queuenum++;//记录从队列中输出的顶点的个数
            q.pop();
            for (temp = g.v[tmp].first; temp; temp = temp->next)
            {
                if (--g.v[temp->argv].rudu == 0)
                    q.push(temp->argv);

            }
        }
        if (queuenum < g.n)//没有完全输出则说明存在环 
            output = 0;
        cout << output << endl;
        while (!q.empty())
            q.pop();
        cin >> n1;
        cin >> m1;
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hebastast

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值