BZOJ4012【拓扑排序】

/* I will wait for you*/

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <string>
#define make make_pair
#define fi first
#define se second

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;

const int maxn = 100010;
const int maxm = 1010;
const int maxs = 26;
const int inf = 0x3f3f3f3f;
const int P = 1000000007;
const double error = 1e-9;

inline int read()
{
	int x = 0, f = 1;
	char ch = getchar();
	while (ch <= 47 || ch >= 58)
		f = (ch == 45 ? -1 : 1), ch = getchar();
	while (ch >= 48 && ch <= 57)
		x = x * 10 + ch - 48, ch = getchar();
	return x * f;
}

struct edge
{
	int v, next;
} e[maxn];

int n, m, cnt, tot, head[maxn], deg[maxn], ans[maxn], del[maxn];

priority_queue<int> q;

void insert(int u, int v)
{
	e[cnt] = (edge) {v, head[u]}, head[u] = cnt++;
}

void init()
{
	tot = cnt = 0;
	memset(deg, 0, sizeof deg);
	memset(head, -1, sizeof head);
	memset(del, 0, sizeof del);
	
	while (!q.empty())
		q.pop();
}

int main()
{
	int t = read();

	while (t--) {
		n = read(), m = read(), init();

		for (int i = 1; i <= m; i++) {
			int u = read(), v = read();
			insert(v, u), deg[u]++;
		}

		for (int i = 1; i <= n; i++)
			if (deg[i] == 0)
				q.push(i);

		while (!q.empty()) {
			int u = q.top(); q.pop();
			ans[++tot] = u;

			for (int i = head[u]; i != -1; i = e[i].next) {
				int v = e[i].v;
				if (!del[v]) {
					deg[v]--;
					if (deg[v] == 0)
						del[v] = 1, q.push(v);
				}
			}
		}

		if (tot != n)
			printf("Impossible!\n");
		else {
			for (int i = n; i >= 1; i--)
				printf("%d ", ans[i]);
			putchar(10);
		}
	}

	return 0;
}

你可能感兴趣的:(BZOJ4012【拓扑排序】)