bzoj 4010 [HNOI2015]菜肴制作 贪心+堆+拓扑排序

题面

题目传送门

解法

直接做似乎不太好做

考虑倒着做,将边反向,然后求出字典序最大的拓扑序,最后将这个拓扑序翻转即为答案

为什么这个是正确的??

感觉理性分析一下就可以了吧

时间复杂度:\(O(n\ log\ n)\)

代码

#include <bits/stdc++.h>
#define N 100010
using namespace std;
template <typename node> void chkmax(node &x, node y) {x = max(x, y);}
template <typename node> void chkmin(node &x, node y) {x = min(x, y);}
template <typename node> void read(node &x) {
	x = 0; int f = 1; char c = getchar();
	while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
	while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
struct Edge {
	int next, num;
} e[N * 3];
int n, m, cnt, s[N], ans[N];
void add(int x, int y) {
	e[++cnt] = (Edge) {e[x].next, y};
	e[x].next = cnt;
}
int topsort() {
	int len = 0;
	priority_queue <int> h;
	for (int i = 1; i <= n; i++)
		if (!s[i]) h.push(i);
	while (!h.empty()) {
		int x = h.top(); h.pop(); ans[++len] = x;
		for (int p = e[x].next; p; p = e[p].next) {
			int k = e[p].num; s[k]--;
			if (!s[k]) h.push(k);
		}
	}
	return len == n;
}
int main() {
	int T; read(T);
	while (T--) {
		read(n), read(m); cnt = n;
		for (int i = 1; i <= n; i++)
			e[i].next = 0, s[i] = 0;
		for (int i = 1; i <= m; i++) {
			int x, y; read(x), read(y);
			add(y, x), s[x]++;
		}
		if (topsort()) {
			for (int i = 1; i <= n; i++)
				cout << ans[n - i + 1] << ' ';
			cout << "\n";
		} else cout << "Impossible!\n";
	}
	return 0;
}

posted @ 2018-08-14 18:27  谜のNOIP  阅读(97)  评论(0编辑  收藏  举报