跳到正文

个人记录

123456789

hyx18008067696约 1 分钟
原文
文章信息与版本

文章信息

发布
2024年8月9日
收录
2026年11月17日
更新
2026年11月17日
篇幅
约 1 分钟
获赞
1

版本

  1. v1当前
C++
# include<bits/stdc++.h>
using namespace std;
const int N=50005;
int e[N][N],tp[N],din[N],n,m;
int idx=1,idx2=1;
queue<int> q;
bool toposort(){
	for(int i=1;i<=n;i++){
		if(din[i]==0) q.push(i);
	}
	while(!q.empty()){
		int f=q.front();
		q.pop();
		tp[idx++]=f;
		for(int i=1;i<=n;i++){
			if(--din[e[f][i]]==0) q.push(e[f][i]);
		}
	}
	return idx-1==n;
}
int main(){
	cin >> n >> m;
	for(int i=0;i<m;i++){
		int a,b;
		cin >> a >> b;
		e[a][idx++]=b;
		din[b]++;
	}
	if(!toposort()) cout << -1;
	else{
		for(int i=1;i<idx;i++){
			cout << tp[i] << " ";
		}
	}
	return 0;
}
原文