社区讨论
用数组模拟邻接表,怎么排序噢,请大佬指点
P5318【深基18.例3】查找文献参与者 3已保存回复 3
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 3 条
- 当前快照
- 1 份
- 快照标识符
- @lo2t6ncl
- 此快照首次捕获于
- 2023/10/23 19:22 2 年前
- 此快照最后确认于
- 2023/10/23 19:22 2 年前
CPP
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 1e6 + 10;
int h[N], e[N], ne[N], idx;
bool st[N];
int n, m;
void add (int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
void dfs (int u)
{
st[u] = true; //表示该文章已经看过了!
cout << u << " ";
for (int i = h[u]; ~i; i = ne[i])
{
int v = e[i];
if (st[v]) continue;
dfs (v);
}
}
void bfs (int s)
{
memset (st, false, sizeof (st));
queue<int> q;
q.push(s);
while (q.size())
{
auto t = q.front();
q.pop();
cout << t << " ";
for (int i=h[t]; ~i; i = ne[i])
{
int v = e[i];
if (!st[v]){
st[v] = true;
q.push(v);
}
}
}
}
int main()
{
cin >> n >> m; //n个点,m条边!
memset(h, -1, sizeof h);
while (m -- )
{
int a, b;
cin >> a >> b;
add(a, b);
}
dfs (1);
puts("");
bfs (1);
return 0;
}
回复
共 3 条回复,欢迎继续交流。
正在加载回复...