拓扑排序基于DFS

CodeForces - 770C 

拓扑排序dfs版+判环 -https://blog.csdn.net/wjh2622075127/article/details/82712940

#include<cstdio>
#include<iostream>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;

vector<int>ans;
vector<int>v[100010],need;
int dp[100010];
//0 no 
//1 select 在本次topu中已选 
//2 has selected
int flag;
void dfs(int start){
	if(dp[start]==2)
		return;
	dp[start]=1;
	for(int i=0;i<v[start].size();i++){
		if(dp[v[start][i]]==1){
			flag=1;
			return;
		}
		dfs(v[start][i]);
	}
	dp[start]=2;
	ans.push_back(start);
}
int main(){
	int n,k;
	cin>>n>>k;
	for(int i=0;i<k;i++){
		int x;
		cin>>x;
		need.push_back(x);
	}
	for(int i=1;i<=n;i++){
		int num,x;
		cin>>num;
		for(int j=1;j<=num;j++){
			cin>>x;
			v[i].push_back(x);
		}
	}
	for(int i=0;i<k;i++){
		dfs(need[i]);
		if(flag){
			cout<<-1<<endl;
			return 0;
		}
	}
	cout<<ans.size()<<endl;
	for(int i=0;i<ans.size();i++)
		cout<<ans[i]<<" ";
	return 0;
}
发布了11 篇原创文章 · 获赞 8 · 访问量 732

猜你喜欢

转载自blog.csdn.net/qq_41765862/article/details/88529100