Making Dishes (P3243 [HNOI2015]菜肴制作)

Background\text{Background}

I’ve got that Luogu Dialy has been \text{I've got that Luogu Dialy has been }updated\text{updated} this morning.\text{ this morning.}
So I decided to learn Topological Sort.\text{So I decided to learn Topological Sort.}

该死的蚊子,TMD把我的手咬得像耕地一样,昨晚皮肤过敏挣扎到很晚才睡。

Description\text{Description}

You’ve got N dishes and M rules about their orders.\text{You've got }N\text{ dishes and }M\text{ rules about their orders.}
Each rule seems like <i,j>, it means you must do i first before doing j.\text{Each rule seems like }<i,j>,\text{ it means you must do }i\text{ first before doing }j.

You perfer dish 1 first, then dish 2,3, and so on.\text{You perfer dish }1\text{ first, then dish 2,3, and so on.}
Please find an order to do all these dishes, so that you can have dish 1 as quickly as possible.\text{Please find an order to do all these dishes, so that you can have dish 1 as quickly as possible.}
If 2 plans’ 1’s order is the same, than you perfer which can have 2 as quickly as\text{If 2 plans' 1's order is the same, than you perfer which can have 2 as quickly as}
possble (And so on).\text{possble (And so on).}

Solution\text{Solution}

There’s a tips that if you output the lexicographic-ordered plan, you’ll get a WA.\text{There's a tips that if you output the lexicographic-ordered plan, you'll get a WA.}
The correct solution is to create the inverse graph, and output upside down.\text{The correct solution is to create the inverse graph, and output upside down.}

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<queue>

using namespace std;

#define reg register

struct node{
	int x,y,next;
}e[100010];
int len=0;
int T;
int n,m,cnt;
int sx,sy;
int first[100010];
int out[100010];
priority_queue<int> q;
int ans[100010];

void ins(int x,int y){
	e[++len].x=x;e[len].y=y;++out[y];
	e[len].next=first[x];first[x]=len;
}
void Toposort(){
	while(!q.empty()) q.pop();
	for(reg int i=1;i<=n;++i)
		if(!out[i])
			q.push(i);
	while(!q.empty()){
		int x=q.top();q.pop();
		ans[cnt--]=x;
		for(reg int i=first[x];i;i=e[i].next){
			int y=e[i].y;--out[y];
			if(!out[y])
				q.push(y);
		}
	}
}
int main(){
	scanf("%d",&T);
	while(T--){
		memset(first,0,sizeof(first));len=0;
		memset(out,0,sizeof(out));
		scanf("%d%d",&n,&m);
		for(reg int i=1;i<=m;++i){
			scanf("%d%d",&sx,&sy);
			ins(sy,sx);
		}
		cnt=n;
		Toposort();
		if(!cnt){
			for(reg int i=1;i<=n;++i)
				printf("%d ",ans[i]);
			puts("");
		}
		else
			printf("Impossible!\n");
	}
}
posted @ 2019-04-28 12:01  TeacherDai  阅读(177)  评论(0)    收藏  举报