Code:
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
#define MAXN 100005
int n, m;
vector <int> p[MAXN];
bool read[MAXN];
void dfs(int x)
{
cout << x << ' ';
for (int i = 0; i < p[x].size(); i++)
if (!read[p[x][i]]) {
read[p[x][i]] = 1;
dfs(p[x][i]);
}
}
void bfs(int x) {
queue <int> q;
q.push(x);
while (!q.empty()) {
x = q.front();
q.pop();
cout << x << " ";
for (int i = 0; i < p[x].size(); i++)
if (!read[p[x][i]]) {
read[p[x][i]] = 1;
q.push(p[x][i]);
}
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= m; i++)
{
int u, v;
cin >> u >> v;
p[u].push_back(v);
}
read[1] = 1;
memset (read, 0, sizeof(read));
dfs(1);
cout << endl;
memset (read, 0, sizeof(read));
bfs(1);
return 0;
}
dfs是照着书写的,样例通过,提交爆零,不知为何?
