20pts?
查看原帖
20pts?
1499743
ma_rui楼主2025/8/29 12:30

看过其他讨论区了,该改的也都改了呀

#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
const int N=1e5+5,INF=0x3f3f3f3f,MOD=1e9+7;
const int dx[]={1,-1,0,0},dy[]={0,0,1,-1};
typedef long long LL;
int n,m,x,y;
vector<int>a[N];
vector<bool>dvis(N),bvis(N);
void dfs(int x){
	cout<<x<<" ";
	for(auto s:a[x]){
		if(!dvis[s]){
			dvis[s] = 1;
			dfs(s);
		}
	}
}
void bfs(int x){
	queue<int>q;
	q.push(1);
	while(!q.empty()){
		int k=q.front();
		q.pop();
		cout<<k<<" ";
		for(auto s:a[k]){
			if(!bvis[s]){
				bvis[s] = 1;
				q.push(s);
			}
		}
	}
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(nullptr),cout.tie(nullptr);
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		cin>>x>>y;
		a[x].push_back(y);
	}
	for(int i=1;i<=n;i++)sort(a[i].begin(),a[i].end());
	dvis[1] = bvis[1] = 1;
	dfs(1);
	cout<<endl;
	bfs(1);
	return 0;
}

2025/8/29 12:30
加载中...