【洛谷习题】P5318 【深基18.例3】查找文献

题目描述

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

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

这边是已经整理好的参考文献关系图,其中,文献 X → Y 表示文章 X 有参考文献 Y。不保证编号为 1 的文章没有被其他文章引用。
在这里插入图片描述
请对这个图分别进行 DFS 和 BFS,并输出遍历结果。如果有很多篇文章可以参阅,请先看编号较小的那篇(因此你可能需要先排序)。

输入格式

输出格式

思路与解法

一道标准的遍历图问题,并且需要用dfs和bfs两种方式实现。而节点数在10的五次方范围,用邻接矩阵存储会超,所以存储改用vector数组。

完整源码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>

using namespace std;

int n, m;
int seen[10005];		//是否读过该博客
vector<int> lines[10005];

void dfs(int thisIdx) {
	if (seen[thisIdx] == 1)return;
	cout << thisIdx << " ";
	seen[thisIdx] = 1;
	for (int i = 0; i < lines[thisIdx].size(); i++) {
		dfs(lines[thisIdx][i]);
	}
}

bool pushNode(queue<int> &que,int val) {
	if (seen[val] == 1)return false;
	que.push(val);
	seen[val] = 1;
	return true;
}
void bfs(int thisIdx) {
	queue<int> que;
	pushNode(que, thisIdx);
	while (que.empty() == false) {
		int tmp = que.front();
		que.pop();
		cout << tmp << " ";
		for (int i = 0; i < lines[tmp].size(); i++) {
			pushNode(que, lines[tmp][i]);
		}
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int t1, t2;
	cin >> n >> m;
	//读入箭头
	for (int i = 1; i <= m; i++) {
		cin >> t1 >> t2;
		lines[t1].push_back(t2);
	}
	//排序箭头
	for (int i = 1; i <= n; i++)
		sort(lines[i].begin(),lines[i].end());
	dfs(1);
	cout << endl;
	memset(seen, '\0', sizeof(seen));
	bfs(1);
	cout << endl;

	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值