0pts求助
查看原帖
0pts求助
973480
封禁用户楼主2024/10/1 19:15
#include<bits/stdc++.h>
using namespace std;
vector<int> graph[100001];
int n,m;
bool book[100001],bbook[100001];
int q[100001],head=1,tail=1;
bool dbool=false;
void dfs(int v){
	if(dbool) return;
	cout << v << " ";
	book[v]=true;
	dbool=true;
	for(int i=1;i<=n;i++){
		if(!book[i]){
			dbool=false;
			break;
		}
	}
	if(dbool) return;
	for(auto i=graph[v].begin();i!=graph[v].end();i++){
		if(!book[*i]) dfs(*i);
	}
	return;
}
int main(){
	cin >> n >> m;
	for(int i=1;i<=n;i++){
		book[i]=false;
        bbook[i]=false;
	}
	for(int i=1;i<=m;i++){
		int x,y;
		cin >> x >> y;
		graph[x].push_back(y);
	}
	dfs(1);
	cout << endl;
	q[tail]=1;
    bbook[1]=true;
	while(head<=tail){
		cout << q[head] << " ";
		int v=q[head];
		for(auto i=graph[v].begin();i!=graph[v].end();i++){
			if(!bbook[*i]) q[++tail]=*i,bbook[*i]=true;;
        }
		head++;
	}
	return 0;
}
2024/10/1 19:15
加载中...