welken @ 2024-11-16 15:50:24
#include <bits/stdc++.h>
#define MAXN 100005
using namespace std;
vector<int> adj[MAXN];
bool Dvisited[MAXN];
bool Bvisited[MAXN];
queue<int> q;
void dfs(int x)
{
cout << x << " ";
Dvisited[x] = 1;
int sz = adj[x].size();
for (int i = 0; i < sz; ++i)
{
if(!Dvisited[adj[x][i]])
{
dfs(adj[x][i]);
}
}
}
void bfs()
{
q.push(1);
Bvisited[1] = 1;
while(!q.empty())
{
int x = q.front();
cout << x << " ";
q.pop();
int sz = adj[x].size();
for (int i = 0; i < sz; ++i)
{
if (Bvisited[adj[x][i]] == 0)
{
Bvisited[adj[x][i]] = 1;
q.push(adj[x][i]);
}
}
}
}
int main()
{
ios::sync_with_stdio(0); cin.tie(0);
int n, m; cin >> n >> m;
for (int i = 0; i < m; ++i)
{
int x, y;
cin >> x >> y;
adj[x].push_back(y);
}
memset(Bvisited, 0,sizeof(Bvisited));
memset(Dvisited, 0,sizeof(Dvisited));
dfs(1);
cout << endl;
bfs();
return 0;
}
求大佬调,这段代码我看了很多次都觉得是对的,实在是一头雾水
by welken @ 2024-11-16 15:51:41
补充:@welken https://www.luogu.com.cn/problem/P5318 P5318题