#5 #6 TLE求调
查看原帖
#5 #6 TLE求调
638084
szhqwq楼主2022/12/23 16:59

代码如下

#include <bits/stdc++.h>

using namespace std;

const int N = 1e5 + 10;

int n,m;
int h[N],e[N],ne[N],d[N],idx = 0;
int cnt[N],x = 0;
priority_queue<int> q;

void add(int a,int b) {
	e[++ idx] = b;
	ne[idx] = h[a];
	h[a] = idx;
}

void topsort() {
	for (int i = 1; i <= n; i ++ ) 
		if (!d[i])
			q.push(i);
	while (!q.empty()) {
		int t = q.top();
		q.pop();
		cnt[++ x] = t;
		for (int i = h[t]; i; i = ne[i]) {
			int j = e[i];
			d[j] --;
			if (!d[j]) q.push(j);
		}
	}
}

signed main() {
	ios :: sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int _;
	cin >> _;
	while (_ -- ) {
		cin >> n >> m;
		x = 0;
		memset(d,0,sizeof d);
		memset(h,0,sizeof h);
		while (!q.empty()) q.pop();
		bool falg = false;
		for (int i = 1; i <= m; i ++ ) {
			int x,y;
			cin >> x >> y;
			add(y,x);
			d[x] ++;
			if (x == y) falg = true;
		}
		if (falg) cout << "Impossible!" << endl;
		topsort();
		if (x < n) cout << "Impossible!" << endl;
		else {
			for (int i = n; i >= 1; i -- ) cout << cnt[i] << " ";
			cout << endl;
		}
	}
	return 0;
}
2022/12/23 16:59
加载中...