用邻接表存的图,思路也挺正确的,样例也过了,求大佬帮忙debug
#include <bits/stdc++.h>
using namespace std;
struct edge {
int u, v;
};
vector<vector<edge> > e;
int n, m;
bool cmp(edge a, edge b) {
return a.v < b.v;
}
void dfs(int x, int* T) {
if (T[x]) return;
T[x] = 1;
cout << x << " ";
for (edge ei : e[x]) {
dfs(ei.v, T);
}
}
void bfs() {
queue<int> q;
q.push(1);
int T[n + 1] = {};
while (!q.empty()) {
int x = q.front();
q.pop();
if (T[x]) continue;
T[x] = 1;
cout << x << " ";
for (edge ei : e[x]) q.push(ei.v);
}
cout << endl;
}
int main() {
cin >> n >> m;
e = vector<vector<edge> >(n + 1, vector<edge>(0));
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
e[u].push_back((edge) {u, v});
}
for (int i = 1; i <= n; i++) {
auto es = e[i];
if (es.size() > 1)
sort(es.begin(), es.end(), cmp);
}
int T[n + 1] = {};
dfs(1, T);
cout << endl;
bfs();
return 0;
}