U107394 拓扑排序模板

//https://www.luogu.com.cn/problem/U107394
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10,M=N;
int n,m;
int head[N],Next[M],to[M],cnt;
int indegree[N],ans[N];
int heap[N];
int heapSize;
void build(){
    cnt=1;
    heapSize=0;
    memset(head,0,sizeof head);
	memset(indegree,0,sizeof indegree);
}
void addEdge(int u,int v){
    Next[cnt]=head[u];
    to[cnt]=v;
    head[u]=cnt++;
}
void push(int num){
	int i=heapSize++;
	heap[i]=num;
	while(heap[i]<heap[(i-1)/2]){
		swap(heap[i],heap[(i-1)/2]);
		i=(i-1)/2;
	}
}
int pop(){
	int ans=heap[0];
	heap[0]=heap[--heapSize];
	int i=0,l=1;
	while (l < heapSize) {
		int best=l+1<heapSize&&heap[l + 1]<heap[l]?l+1:l;
		best=heap[best]<heap[i]?best:i;
		if(best==i) break;
		swap(heap[best],heap[i]);
		i=best;
		l=i*2+1;
	}
	return ans;
}
bool isEmpty(){
	return heapSize==0;
}
bool topoSort(){
    for(int i=1;i<=n;i++) if(indegree[i]==0) push(i);
    int fill=0;
    while(!isEmpty()){
        int u=pop();
        ans[++fill]=u;
        for(int ei=head[u],v;ei;ei=Next[ei]){
            v=to[ei];
            if(--indegree[v]==0) push(v);
        }
    }
    return fill==n;
}
int main(){
    scanf("%d%d",&n,&m);
    build();
    for(int i=1,u,v;i<=m;i++){
        scanf("%d%d",&u,&v);
        indegree[v]++;
        addEdge(u,v);
    }
    if(!topoSort()) puts("-1");
    else{
        for(int i=1;i<=n;i++) printf("%d ",ans[i]);
    }
    return 0;
}
posted @ 2025-05-01 17:57  九三青梧  阅读(10)  评论(0)    收藏  举报