题目链接: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;
}