跳到正文

个人记录

题解 P3243 [HNOI2015]菜肴制作

hellhell约 4 分钟
原文
文章信息与版本

文章信息

发布
2021年5月4日
收录
2026年8月21日
更新
2026年8月21日
篇幅
约 4 分钟
获赞
1

版本

  1. v1当前

题目大意

一共 NN 道菜,编号为 1−N1-N,编号越小,菜的质量越高。给出 MM 条限制 <i,j><i,j>,表示 ii 号菜肴制作必须先于 jj 号菜肴。 一共 DD 组询问,对于每组询问求出最优的做菜顺序,使得质量高的菜,尽量早做完。如果无解,输出 “Impossible!”。

样例:共 44 道菜肴,两条限制 <3,1>,<4,1><3,1>,<4,1>,那么制作顺序是 3,4,1,23,4,1,2。

N,M≤105N,M \leq 10^5,D≤3D\leq3。

思路分析

贪心地去想,在满足条件的情况下,最后一个数字越大,答案一定更优。

假设可以确定最后一个数字是 xx,那比 xx 小的数字越靠前越优,比 xx 大的,放在 xx 的后面一定更优,但是确定了最后一个是 xx 所以,比 xx 大的数字越靠后越优。

由此得出,在满足 MM 条限制的情况下,答案序列的反序列的字典序要最大。

反向建图,将拓扑排序中的队列换成大根堆,倒序输出拓扑序即可。

代码实现

C++
#include <bits/stdc++.h>
#define int long long
#define N 100005

using namespace std;

int read(){
    int res=0;
    char ch=getchar();
    int f=1;
    while(ch<'0' || ch>'9'){
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(ch>='0' && ch<='9'){
        res=res*10+ch-'0';
        ch=getchar();
    }
    return res*f;
}

void out(int x){
    if(x>=10)
        out(x/10);
    putchar(x%10+'0');
}
void out1(int x){
    if(x<0)
        putchar('-');
    out(abs(x));
}
void out2(int x){
    out1(x);
    putchar('\n');
}

int d;
int n,m;
int x,y;

struct node{
    int to;
    int next;
}edge[N];
int head[N];
int cnt;

void add(int u,int v){
    edge[++cnt].to=v;
    edge[cnt].next=head[u];
    head[u]=cnt;
}

int ind[N];

int topo[N];
int tag;

priority_queue<int,vector<int>,less<int> > q;

void TopoSort(){
    for(int i=1;i<=n;i++){
        if(ind[i]==0){
            q.push(i);
        }
    }
    while(!q.empty()){
        int now=q.top();
        q.pop();
        topo[++tag]=now;
        for(int i=head[now];i;i=edge[i].next){
            int v=edge[i].to;
            ind[v]--;
            if(ind[v]==0)
                q.push(v);
        }
    }
}

signed main(){
    d=read();
    while(d--){
        n=read(),m=read();
        tag=0;
        cnt=0;
        memset(ind,0,sizeof(ind));
        memset(head,0,sizeof(head));
        for(int i=1;i<=m;i++){
            x=read();
            y=read();
            add(y,x);
            ind[x]++;
        }
        TopoSort();
        if(tag!=n){
            cout<<"Impossible!"<<endl;
        }
        else{
            for(int i=tag;i>=1;i--){
                printf("%lld ",topo[i]);
            }
            cout<<endl;
        }
    }
    return 0;
}
原文