#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 1e5 + 5;
int h[N], e[N], ne[N], idx, n, m, a, b, res[N], top;
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
struct node
{
int d, lim, id;
bool operator>(const node &t) const
{
if (t.lim == lim && t.d == d)
return id > t.id;
else if (t.d == d)
return lim > t.lim;
return d > t.d;
}
} t[N];
priority_queue<node, vector<node>, greater<node>> q;
bool topsort()
{
node p;
int id, j;
while (q.size())
{
p = q.top(), q.pop();
if (p.d)
break;
id = p.id, res[++top] = id;
for (int i = h[id]; ~i; i = ne[i])
j = e[i], t[j].d--, q.push(t[j]);
}
return top == n;
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0);
int T;
cin >> T;
while (T--)
{
cin >> n >> m, memset(h, -1, sizeof(h)), top = idx = 0;
for (int i = 1; i <= n; i++)
t[i].d = 0, t[i].id = t[i].lim = i;
while (m--)
{
cin >> a >> b, add(a, b);
t[a].lim = min(t[a].lim, t[b].lim), t[b].d++;
}
for (int i = 1; i <= n; i++)
q.push(t[i]);
if (topsort())
for (int i = 1; i <= n; i++)
cout << res[i] << " ";
else
cout << "Impossible! ";
cout << "\n";
}
}
我寻思一直维护一个堆来做的,难道一些排序的性质推错了?