【深基18.例3】查找文献(C++,图的遍历)

题目描述

小K 喜欢翻看洛谷博客获取知识。每篇文章可能会有若干个(也有可能没有)参考文献的链接指向别的博客文章。小K 求知欲旺盛,如果他看了某篇文章,那么他一定会去看这篇文章的参考文献(如果他之前已经看过这篇参考文献的话就不用再看它了)。

假设洛谷博客里面一共有 n ( n ≤ 1 0 5 ) n(n\le10^5) n(n105) 篇文章(编号为 1 到 n n n)以及 m ( m ≤ 1 0 6 ) m(m\le10^6) m(m106) 条参考文献引用关系。目前小 K 已经打开了编号为 1 的一篇文章,请帮助小 K 设计一种方法,使小 K 可以不重复、不遗漏的看完所有他能看到的文章。

这边是已经整理好的参考文献关系图,其中,文献 X → Y 表示文章 X 有参考文献 Y。不保证编号为 1 的文章没有被其他文章引用。

请对这个图分别进行 DFS 和 BFS,并输出遍历结果。如果有很多篇文章可以参阅,请先看编号较小的那篇(因此你可能需要先排序)。

输入格式

m + 1 m+1 m+1 行,第 1 行为 2 个数, n n n m m m,分别表示一共有 n ( n ≤ 1 0 5 ) n(n\le10^5) n(n105) 篇文章(编号为 1 到 n n n)以及 m ( m ≤ 1 0 6 ) m(m\le10^6) m(m106) 条参考文献引用关系。

接下来 m m m 行,每行有两个整数 X , Y X,Y X,Y 表示文章 X 有参考文献 Y。

输出格式

共 2 行。
第一行为 DFS 遍历结果,第二行为 BFS 遍历结果。

样例 #1

样例输入 #1

8 9
1 2
1 3
1 4
2 5
2 6
3 7
4 7
4 8
7 8

样例输出 #1

1 2 5 6 3 7 8 4 
1 2 3 4 5 6 7 8

解题思路:

由于需要优先到达编号小的节点,所以采用优先队列,用vector存图

深度优先搜索思路如下

void dfs(int index) {//index为当前位置
	while (!queue[index].empty()) {
		if (/* 已经来过 */) queue[index].pop(); 
        else dfs(index);
    }
}

广度优先搜索思路如下

void bfs(int index) {//index为起始位置
	while (/* bfs队列不为空 */) {
		while (!queue[/* bfs首元素 */].empty()) {
			if (/* 已经来过 */) queue.pop();
			else /* queue.top()插入bfs队列 */;
		}
		/* bfs队首出队 */;
	}
}

实现代码如下

#include <iostream>
#include <memory.h>
#include <queue>
using namespace std;
const int max_n = 1e5;
const int max_m = 1e6;

priority_queue<int, vector<int>, greater<int>>edges[max_n + 1];
priority_queue<int, vector<int>, greater<int>>edges_bfs[max_n + 1];
queue<int>bfs_queue;
bool book[max_n + 1] = { false };

void dfs(int index) {
	while (!edges[index].empty()) {
		if (book[edges[index].top()]) {
			edges[index].pop();
			continue;
		}
		int temp = edges[index].top();
		edges[index].pop();
		book[temp] = true;
		cout << temp << ' '; dfs(temp);
	}
}

void bfs(int index) {
	cout << index << ' ';
	bfs_queue.push(index);
	book[index] = true;
	while (!bfs_queue.empty()) {
		int head = bfs_queue.front();
		while (!edges_bfs[head].empty()) {
			if (book[edges_bfs[head].top()]) {
				edges_bfs[head].pop();
				continue;
			}
			int temp = edges_bfs[head].top();
			edges_bfs[head].pop();
			cout << temp << ' ';
			bfs_queue.push(temp);
			book[temp] = true;
		}
		bfs_queue.pop();
	}
}

int main() {
	int n, m, u, v;
	cin >> n >> m;
	for (int i = 0; i < m; i++) {
		cin >> u >> v;
		edges[u].push(v);
		edges_bfs[u].push(v);
	}
	book[1] = true;
	cout << 1 << ' '; dfs(1); cout << endl;
	memset(book, false, sizeof(bool) * (max_n + 1));
	bfs(1);
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WitheredSakura_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值