当前位置:网站首页>BDF application - topology sequence

BDF application - topology sequence

2022-07-05 03:56:00 jigsaw_ zyx

Problem description
Given a n A little bit m Directed graph of strip edge , The number of points is 1 To n, There may be double edges and self rings in the graph .

Please output any topological sequence of the directed graph , If the topological sequence does not exist , The output -1.

If a sequence consisting of all the points in the graph A Satisfy : For each edge in the graph (x, y),x stay A All appear in y Before , said A Is a topological sequence of the graph .

Input format
The first line contains two integers n and m

Next m That's ok , Each line contains two integers x and y, Indicates that there is a from point x point-to-point y The directed side of (x, y).

Output format
All in one line , If there is a topological sequence , Then output any legal topological sequence .

Otherwise output -1.

Data range
1≤n,m≤105
sample input :
3 3
1 2
2 3
1 3
sample output :
1 2 3

Code

#include<bits/stdc++.h>
using namespace std;

const int N=100100;
int n,m;
int h[N],e[N],ne[N],idx=0;// Linked list record chart  
int q[N],d[N];// Simulation queue  、 Record the degree of penetration  

void add(int a,int b){
    // Save map  
	e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}

bool topsort(){
    // A topological sort  
	int hh=0,tt=-1;
	
	for(int i=1;i<=n;i++)
	  if(d[i]==0)
	    q[++tt]=i;
	    
	while(hh<=tt){
    
		int k=q[hh++];
		
		for(int i=h[k];i!=-1;i=ne[i]){
    
			int j=e[i];
			d[j]--;
			if(d[j]==0) q[++tt]=j;
		}
	}
	
	return tt==n-1;
}

int main(){
    
	cin>>n>>m;
	
	memset(h,-1,sizeof h);
	
	while(m--){
    
		int x,y;
		cin>>x>>y;
		add(x,y);
		d[y]++;
	}
	
	if(topsort()){
    
		for(int i=0;i<n;i++) cout<<q[i]<<" ";
		puts("");
	}else cout<<-1;
	
	return 0;
}
原网站

版权声明
本文为[jigsaw_ zyx]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140718477739.html