题目描述
众所周知, TT 是一位重度爱猫人士,他有一只神奇的魔法猫。
有一天,TT 在 B 站上观看猫猫的比赛。一共有 N 只猫猫,编号依次为1,2,3,…,N进行比赛。比赛结束后,Up 主会为所有的猫猫从前到后依次排名并发放爱吃的小鱼干。不幸的是,此时 TT 的电子设备遭到了宇宙射线的降智打击,一下子都连不上网了,自然也看不到最后的颁奖典礼。
不幸中的万幸,TT 的魔法猫将每场比赛的结果都记录了下来,现在他想编程序确定字典序最小的名次序列,请你帮帮他。
Input
输入有若干组,每组中的第一行为二个数N(1<=N<=500),M;其中N表示猫猫的个数,M表示接着有M行的输入数据。接下来的M行数据中,每行也有两个整数P1,P2表示即编号为 P1 的猫猫赢了编号为 P2 的猫猫。
Output
给出一个符合要求的排名。输出时猫猫的编号之间有空格,最后一名后面没有空格!
其他说明:符合条件的排名可能不是唯一的,此时要求输出时编号小的队伍在前;输入数据保证是正确的,即输入数据确保一定能有一个符合要求的排名。
Sample Input
4 3
1 2
2 3
4 3
Sample Output
1 2 4 3
解题思路
本题属于典型的拓扑排序问题,直接使用Kahn算法求解即可。
首先需要两个队列,一个用来保存每次入度为0的点集,另一个用来保存排好的序。由于题目要求编号小的数据在前面输出,那么第一个集合需要使用优先级队列来保存,第二个可以使用vector来保存。
先遍历所有点,将入度为0的点加入优先级队列,然后从中取出一个点并删除,将该店加入vector中,并将该点连接的点的入度-1,再判断这些点是否入度为0,若为0则加入优先级队列。最后依次输出vector中的元素。
代码
#include<iostream>
#include<queue>
#include<vector>
#include<utility>
#include<cstring>
using namespace std;
const int maxm=510,maxn=1e6;
int head[maxm],in_deg[maxm];//记录每一个点的入度
int N,M,p1,p2;
int