题意:
众所周知, TT 是一位重度爱猫人士,他有一只神奇的魔法猫。
有一天,TT 在 B 站上观看猫猫的比赛。一共有 N 只猫猫,编号依次为1,2,3,…,N进行比赛。比赛结束后,Up 主会为所有的猫猫从前到后依次排名并发放爱吃的小鱼干。不幸的是,此时 TT 的电子设备遭到了宇宙射线的降智打击,一下子都连不上网了,自然也看不到最后的颁奖典礼。
不幸中的万幸,TT 的魔法猫将每场比赛的结果都记录了下来,现在他想编程序确定字典序最小的名次序列,请你帮帮他。
思路:
胜负关系可以构成一张有向无环图,p1赢了p2等价于有向边(p1,p2),在最终的名次序列里p1要在p2的前面。
求拓扑序列:计算所有顶点的入度,当入度为0时将顶点加入到小根堆。当小根堆不为空时,取出一个顶点u,将其加入到答案序列中,然后对所有的(u,v),将顶点v入度-1,如果v入度为0,加入小根堆。最后按需输出答案。
代码:
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N = 510;
int head[N], ind[N], tot;
struct Edge {
int to, next;
}e[N * N];
void add(int x, int y)
{
e[++tot].next = head[x];
e[tot].to = y;
head[x] = tot;
ind[y]++;
}
void ini()
{
memset(head, 0, sizeof(head));
memset(ind, 0, sizeof(ind));
tot = 0;
}
void kahn(int n)
{
priority_queue<int> q;
for (int i = 1; i <= n; i++)
if (ind[i] == 0)
q.push(-i);
vector<int> ans;
while (!q.empty())
{
int u = -q.top();
q.pop();
ans.push_back(u);
for (int i = head[u]; i != 0; i = e[i].next)
{
int v = e[i].to;
if (--ind[v] == 0)q.push(-v);
}
}
int s = ans.size();
cout << ans[0];
for (int i = 1; i < s; i++)
cout << " " << ans[i];
cout << endl;
}
int main()
{
int n, m;
while (cin >> n && cin >> m)
{
ini();
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a;
cin >> b;
add(a, b);
}
kahn(n);
}
}