中文题目,上菜问题
题目中要求了哪道菜要在哪道菜之前先上,一开始觉得拓扑排序做不了,然后就上了个差分约束,然后就超时了。。。
题目中要求:(1)在满足所有限制的前提下,1 号菜肴“尽量”优先制作;(2)在满足所有限制,1
号菜肴“尽量”优先制作的前提下,2号菜肴“尽量”优先制作;(3)在满足所有限
制,1号和2号菜肴“尽量”优先的前提下,3号菜肴“尽量”优先制作;(4)在满
足所有限制,1 号和 2 号和 3 号菜肴“尽量”优先的前提下,4 号菜肴“尽量”优
先制作;(5)以此类推。
所以拓扑排序的建边不能由先上的菜连向后上的菜,因为如样例中的<5,2>、 <4,3>,我们要依据的是后上的那道菜的序号来对那些没有拓扑关系的菜排序,所以正解是,由后上的菜向先上的菜建边,然后逆序做拓扑排序,用的优先队列实现的。
#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdio.h>
#include<vector>
#include<string>
#include<cmath>
#include<set>
#include<queue>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
//const int mod = 1000000007;
const int maxm = 105005;
const int maxn = 100005;
const int M = 25;
int n,m;
int deg[maxn];
int to[maxm], nex[maxm];
int head[maxn], tot;
vector<int> ans;
struct nnn{
int p;
nnn(int num){ p = num; }
bool operator<(const nnn &b)const{
return p<=b.p;
}
};
priority_queue<nnn> que;
void add(int a, int b){
to[++tot] = b;
nex[tot] = head[a];
head[a] = tot;
}
int main() {
int t,x,y;
scanf("%d", &t);
while (t--){
ans.clear();
memset(head, -1, sizeof(head));
memset(deg, 0, sizeof(deg));
tot = 0;
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++){
scanf("%d%d", &x, &y);
add(y, x);
deg[x]++;
}
for (int i = 1; i <= n; i++){
if (deg[i] == 0){
que.push(i);
}
}
while (!que.empty()){
int cnt = que.top().p; que.pop();
ans.push_back(cnt);
for (int i = head[cnt]; i != -1; i = nex[i]){
deg[to[i]]--;
if (deg[to[i]] == 0){ que.push(to[i]); }
}
}
int ss = ans.size();
if (ss<n - 1){ printf("Impossible!\n"); }
else{
for (int i = ss - 1; i >= 0; i--){
printf("%d ", ans[i]);
}
printf("\n");
}
}
return 0;
}