Luogu3243 [HNOI2015]菜肴制作 (拓扑排序)

题面毒人,其实就是叫你反图跑拓扑

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int  a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int  a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long

//#define ON_DEBUG

#ifdef ON_DEBUG

#define D_e_Line printf("\n\n----------\n\n")
#define D_e(x)  cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt","r",stdin);

#else

#define D_e_Line ;
#define D_e(x)  ;
#define Pause() ;
#define FileOpen() ;

#endif

struct ios{
    template<typename ATP>ios& operator >> (ATP &x){
        x = 0; int f = 1; char c;
        for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-')  f = -1;
        while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
        x*= f;
        return *this;
    }
}io;
using namespace std;
#include<queue>

const int N = 100007;

struct Edge{
	int nxt, pre;
}e[N << 1];
int head[N], cntEdge;
inline void add(int u, int v){
	e[++cntEdge] = (Edge){ head[u], v}, head[u] = cntEdge;
}

int in[N];
priority_queue<int>q;
int ans[N];
int main(){
	int Tasks;
	io >> Tasks;
	int flag = 0;
	while(Tasks--){
		int n, m;
		io >> n >> m;
		if(flag){
			R(i,0,n){
				head[i] = in[i] = 0;
			}
			cntEdge = 0;
		}
		
		R(i,1,m){
			int u, v;
			io >> u >> v;
			add(v, u);
			++in[u];
		}
		
		int tot = 0;
		R(i,1,n){
			if(!in[i]){
				q.push(i);
			}
		}
		while(!q.empty()){
			int u = q.top();
			q.pop();
			ans[++tot] = u;
			for(register int i = head[u]; i; i = e[i].nxt){
				int v = e[i].pre;
				--in[v];
				if(!in[v]){
					q.push(v);
				}
			}
		}
		
		if(tot != n){
			printf("Impossible!\n");
			flag = 1;
			continue;
		}
		
		nR(i,n,1){
			printf("%d ", ans[i]);
		}
		putchar('\n');
		flag = 1;
	}
	
	return 0;
}

posted @ 2019-07-23 09:28  邱涵的秘密基地  阅读(139)  评论(0编辑  收藏  举报