WEEK 8 B cat cat rushes forward

topic

As we all know, TT is a cat lover who has a magic cat.
One day, TT watched the cat game on station B. There are N cats in total, numbered 1, 2, 3, ..., N to play. After the game, the Up host will rank all the cats from front to back and distribute the favorite dried fish. Unfortunately, at this time, TT's electronic equipment was hit by the cosmic ray of de-smart, and even no Internet access at all, and naturally the final award ceremony could not be seen.
Fortunately, the magic cat of TT recorded the results of each game. Now he wants to program to determine the sequence of the smallest lexicographic order. Please help him.

Input

There are several groups of inputs, and the first row in each group is two numbers N (1 <= N <= 500), M; where N represents the number of cats and cats, and M represents the next M rows of input data. In the next M rows of data, each row also has two integers P1, P2 means that the cat with the number P1 wins the cat with the number P2.

Output

Give a ranking that meets the requirements. There is a space between the cat's numbers when outputting, there is no space after the last one!

Other notes: The ranking that meets the conditions may not be unique. At this time, the team with the lowest number is required to be output first; the input data is guaranteed to be correct, that is, the input data ensures that there can be a ranking that meets the requirements.

Sample Input

4 3
1 2
2 3
4 3

Sample Output

1 2 4 3

Ideas

The win-loss relationship of a cat can be imagined as an edge in a directed graph, a wins b, that is, there is an edge pointing from a to b, and the topological sequence of these points is the final ranking. To output the topological sequence with the smallest lexicographic order, a minimum heap can be used to find the topological sequence.

Code

#include <iostream>
#include <queue>
#include <algorithm>
#include <string.h>

using namespace std;

const int maxn = 505;
struct edge
{
	int to, next;
}e[maxn * 2];
int n, m, inde[maxn], head[maxn], tot;

void add(int x, int y)
{
	e[++tot].to = y;
	e[tot].next = head[x];
	head[x] = tot;
}

void toposort()
{
	priority_queue<int>q;
	while (!q.empty()) 
		q.pop();
	for (int i = 1; i <= n; i++)
		if (inde[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)
			if (--inde[e[i].to] == 0)
				q.push(-e[i].to);
	}
	for (int i = 0; i < ans.size() - 1; i++)
		cout << ans[i] << " ";
	cout << ans[ans.size() - 1] << endl;
}

int main()
{
	while (scanf_s("%d%d",&n,&m)!=EOF) 
	{
		memset(head, 0, sizeof(head));
		memset(inde, 0, sizeof(inde));
		tot = 0;
		for (int i = 1; i <= m; i++) 
		{
			int a, b;
			scanf_s("%d%d", &a, &b);
			add(a, b);
			inde[b]++;
		}
		toposort();
	}
	return 0;
}
Published 32 original articles · praised 0 · visits 669

Guess you like

Origin blog.csdn.net/qq_43814559/article/details/105567864