拓扑排序
拓扑排序(topsort)核心思想:不停找入度为零的点不断删去,并更新其他节点入度直到为空。
适用范围:一些满足一定先后关系的活动排序。
例题:
John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task isonly possible if other tasks have already been executed.
The input will consist of several instances of the problem. Each instance begins with a line containing
two integers, 1 n 100 and m. n is the number of tasks (numbered from 1 to n) and m is the
number of direct precedence relations between tasks. After this, there will be m lines with two integers
i and j, representing the fact that task i must be executed before task j.
An instance with n = m = 0 will nish the input.
For each instance, print a line with n integers representing the tasks in a possible order of execution.
5 4
1 2
2 3
1 3
1 5
0 0
1 4 2 5 3
题意:这就是一个比较典型的拓扑排序的例子。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
int n,m,degree[105],u,v; //degree用于保存入度
int main()
{
while(cin >> n >> m && m+n)
{
vector<int> G[105];
memset(degree,0,sizeof(degree));
for (int i=0;i<m;i++)
{
scanf("%d%d",&u,&v);
G[u].push_back(v);
degree[v]++; //记录v的入度
}
queue<int> q;
for (int i=1;i<=n;i++)
if (!degree[i]) q.push(i); //入度为0直接入队
while(!q.empty())
{
int v=q.front(); q.pop();
printf("%d ",v);
for (int t=0;t<G[v].size();t++)
if (--degree[G[v][t]]==0) //指向的点入度都减一如果减一后为0入队
q.push(G[v][t]);
}
printf("\n");
}
return 0;
}
posted on 2018-04-11 00:46 Radium_1209 阅读(114) 评论(0) 收藏 举报