题目传送门 P5318 【深基18.例3】查找文献
数据再开大就编译错误了
数据开小就20分
20分代码
#include<bits/stdc++.h>
using namespace std;
const int N=1e4;
int arr[N][N];
bool vis[N];
int n,m;
void dfs(int x){
cout << x << ' ';
vis[x] = 1;
for(int j = 1 ; j <= n ; j++){
if(arr[x][j] == 1 && !vis[j]){
dfs(j);
}
}
}
void bfs(int x){
queue<int> q;
q.push(x);
vis[x] = 1;
while(!q.empty()){
int now = q.front();
q.pop();
cout << now << ' ';
for(int j = 1 ; j <= n ; j++){
if(arr[now][j] == 1 && !vis[j]){
vis[j] = 1;
q.push(j);
}
}
}
}
int main(){
cin >> n >> m;
for(int i = 1 ; i <= m ; i++){
int u,v;
cin >> u >> v;
arr[u][v] = 1;
}
dfs(1);
cout << endl;
memset(vis,0,sizeof(vis));
bfs(1);
return 0;
}