样例能过,但全wa了,用的是链表。
#include<iostream>
#include<queue>
using namespace std;
struct ele {
int data = 0;
ele* next = NULL;
};
ele* h[123456], * r[123456];
bool v[123456];
int n, m, i, j;//n个结点,m条边;
void dfs(int x) {
if (v[x])return;
else {
v[x] = 1;
cout << x << ' ';
ele* s = h[x];
while (s->data != 0) {
dfs(s->data);
s = s->next;
}
}
}
void bfs(int x) {
queue<int>que;
que.push(x);
v[x] = 1;
while (!que.empty()) {
ele* s = h[que.front()];
while (s->data != 0) {
if (!v[s->data]) {
v[s->data] = 1;
que.push(s->data);
}
s = s->next;
}
cout << que.front() << ' ';
que.pop();
}
}
void clear(int x) {
for (int j = 1; j <= x; j++) {
v[j] = 0;
}
}
int main() {
cin >> n >> m;
for (i = 1; i <= n; i++) {
h[i] = r[i] = new ele;
}
for (i = 0; i < m; i++) {
cin >> j;
cin >> r[j]->data;
r[j]->next = new ele;
r[j] = r[j]->next;
}
clear(n);
dfs(1);
cout << endl;
clear(n);
bfs(1);
cout << endl;
return 0;
}