10pts求助(玄关
查看原帖
10pts求助(玄关
1287433
__ycy1124__楼主2024/8/18 16:23
#include<bits/stdc++.h>
using namespace std;
vector<int>a[100001];
int rd[100001];
int tot=0;
stack<int>ans;
struct Node{
	int w;
}b[100001];
void work(int x){
	if(x!=1&&b[x].w>b[x/2].w){
		swap(b[x],b[x/2]);
		work(x/2);
	}
}
void work1(int x){
	if(x*2+1<=tot&&b[x].w<b[x*2+1].w&&b[x*2+1].w>b[x*2].w){
		swap(b[x],b[x*2+1]);
		work1(x*2+1);
	}
	else if(x*2+1<=tot&&b[x].w<b[x*2].w){
		swap(b[x],b[x*2]);
		work(x*2);
	}
	else if(x*2==tot&&b[x*2].w>b[x].w){
		swap(b[x],b[x*2]); 
		work1(x*2); 
	}
}
int main(){
	int t;
	int n,m;
	scanf("%d",&t);
	while(t){
		t--;
		scanf("%d%d",&n,&m);
		for(int i=1;i<=n;i++){
			rd[i]=0;
			a[i].clear();
		}
		for(int i=1;i<=m;i++){
			int u,v;
			scanf("%d%d",&u,&v);
			a[v].push_back(u);
			rd[u]++;
		}
		for(int i=1;i<=n;i++){
			if(rd[i]==0){
				b[++tot].w=i;
				work(tot);
			}
		}
		while(tot){
			/*printf("%d\n",b[1].w);
			for(int i=1;i<=n;i++){
				printf("%d ",rd[i]);
			}
			printf("\n");*/
			ans.push(b[1].w);
			int c=b[1].w;
			swap(b[1],b[tot]);
			tot--;
			work1(1);
			for(auto it:a[c]){
				rd[it]--;
				if(rd[it]==0){
					b[++tot].w=it;
					work(tot);
				}
			}
		}
		if(ans.size()==n){
			while(!ans.empty()){
				printf("%d ",ans.top());
				ans.pop();
			}
		}
		else{
			while(!ans.empty()){
				ans.pop();
			}
			printf("Impossible!");
		}
		printf("\n");
	}
	return 0;
} 
2024/8/18 16:23
加载中...