洛谷 #3243. 菜餚製作
阿新 • • 發佈:2018-11-24
題意
做n道菜,要求有些菜必須在有些菜前製作,問字典序最小的製作順序
題解
topsort,用priority_queue,最後反著輸
除錯記錄
判斷Index[n] == 0時少打了個 !
要用priority_queue(因為字典序)
#include <cstdio>
#include <queue>
#include <cstring>
#define maxn 100005
using namespace std;
struct node{
int to, next;
}e[maxn];
int tot, head[ maxn], Index[maxn];
void addedge(int u, int v){e[++tot] = (node){v, head[u]}; head[u] = tot; Index[v]++; }
int ans[maxn], T, n, m, cnt;
void topsort(){
priority_queue <int> q; while (!q.empty()) q.pop();
for (int i = 1; i <= n; i++)
if (!Index[i]) q.push(i);
while (!q.empty()){
int cur = q.top(); q.pop();
ans[++cnt] = cur;
for (int i = head[cur]; i; i = e[i].next){
if (!--Index[e[i].to]) q.push(e[i].to);
}
}
}
int main(){
scanf("%d", &T);
while (T--){
scanf("%d%d", &n, &m);
memset(e, 0, sizeof e); memset(ans, 0, sizeof ans); memset(Index, 0, sizeof Index);
memset(head, 0, sizeof head); tot = 0; cnt = 0;
for (int u, v, i = 1; i <= m; i++){
scanf("%d%d", &u, &v); addedge(v, u);
}
topsort();
if (cnt != n) printf("Impossible!\n");
else{
for (int i = cnt; i >= 1; i--) printf("%d ", ans[i]);
putchar('\n');
}
}
return 0;
}