图论:拓扑排序

10305 – Ordering Tasks

John has n tasks to do. Unfortunately, the tasks are not independent and the execution of one task is only possible if other tasks have already been executed.

Input

The input will consist of several instances of the problem. Each instance begins with a line containing two integers, 1 <= n <= 100 andmn 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 = 0will finish the input.

Output

For each instance, print a line with n integers representing the tasks in a possible order of execution.

Sample Input

5 4
1 2
2 3
1 3
1 5
0 0

Sample Output

1 4 2 5 3

裸的,输出顺序任意,所以DFS做法可以求得。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
typedef long long LL;
using namespace std;
#define REPF( i , a , b ) for ( int i = a ; i <= b ; ++ i )
#define REP( i , n ) for ( int i = 0 ; i < n ; ++ i )
#define CLEAR( a , x ) memset ( a , x , sizeof a )
const int maxn=110;
int mp[maxn][maxn];
int toposort[maxn];
int vis[maxn];
int n,m,cnt;
void dfs(int x)
{
vis[x]=1;
for(int i=1;i<=n;i++)
if(!vis[i]&&mp[x][i]&&i!=x) dfs(i);
toposort[cnt++]=x;
}
void solve()
{
CLEAR(vis,0);
for(int i=1;i<=n;i++)
if(!vis[i]) dfs(i);
}
int main()
{
int x,y;
std::ios::sync_with_stdio(false);
while(cin>>n>>m&&(n+m))
{
CLEAR(mp,0);
while(m–)
{
cin>>x>>y;
mp[x][y]=1;
}
cnt=0;
solve();
for(int i=cnt⑴;i>=0;i–)
printf(i==0?"%d
":"%d ",toposort[i]);
}
return 0;
}

HDU 1285

肯定比赛名次

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13115    Accepted Submission(s): 5264

Problem Description
有N个比赛队(1<=N<=500),编号顺次为1,2,3,。。。。,N进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后顺次排名,但现在裁判委员会不能直接取得每一个队的比赛成绩,只知道每场比赛的结果,即P1赢P2,用P1,P2表示,排名时P1在P2之前。现在请你编程序肯定排名。
 

Input
输入有若干组,每组中的第1行动2个数N(1<=N<=500),M;其中N表示队伍的个数,M表示接着有M行的输入数据。接下来的M行数据中,每行也有两个整数P1,P2表示即P1队赢了P2队。
 

Output
给出1个符合要求的排名。输出时队伍号之间有空格,最后1名后面没有空格。

其他说明:符合条件的排名可能不是唯1的,此时要求输出时编号小的队伍在前;输入数据保证是正确的,即输入数据确保1定能有1个符合要求的排名。

 

Sample Input
波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 本站源码并不保证全部能正常使用,仅供有技术基础的人学习研究,请谨慎下载
8. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!

波比源码 » 图论:拓扑排序

发表评论

Hi, 如果你对这款模板有疑问,可以跟我联系哦!

联系站长
赞助VIP 享更多特权,建议使用 QQ 登录
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡