P5318 【深基18.例3】查找文献

1|0P5318 【深基18.例3】查找文献

1|1基本思路

邻接表实现,结果得为了边有序再专门开一个 vector 预处理完再存边。

而且一开始忘记 vis[1] = true 了!

#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<queue> #include<vector> const int N = 1e6 + 10; int head[N], tot; int vis[N]; std::vector<int> temp[N]; struct Node { int to, next; }edge[N]; bool cmp(int x, int y) { return x > y; } void addEdge(int u, int v) { edge[++tot].to = v; edge[tot].next = head[u]; head[u] = tot; } int n, m; void DFS(int now) { std::cout << now << " "; for (int i = head[now]; i ; i = edge[i].next) { if (!vis[edge[i].to]) { vis[edge[i].to] = true; DFS(edge[i].to); } } } void BFS() { std::cout << std::endl; std::queue<int> q; q.push(1); while(!q.empty()) { int now = q.front();q.pop(); std::cout << now << " "; for (int i = head[now]; i ; i = edge[i].next) { if(!vis[edge[i].to]) { vis[edge[i].to] = true; q.push(edge[i].to); } } } } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); std::cin >> n >> m; for (int i = 1; i <= m; i++) { int x, y; std::cin >> x >> y; temp[x].push_back(y); } for (int i = 1; i <= n; i++) { sort(temp[i].begin(), temp[i].end(), cmp); } for (int i = 1; i <= n; i++) { for (auto u : temp[i]) { addEdge(i, u); } } vis[1] = true; DFS(1); std::memset(vis, 0, sizeof(vis)); vis[1] = true; BFS(); return 0; }

1|2邻接矩阵

vector 实现的邻接矩阵,显然更自然,毕竟存边完直接排序。

#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<queue> #include<vector> const int N = 1e6 + 10; int vis[N]; std::vector<int> edge[N]; int n, m; void DFS(int now) { std::cout << now << " "; for (auto to : edge[now]) { if (!vis[to]) { vis[to] = true; DFS(to); } } } void BFS() { std::cout << std::endl; std::queue<int> q; q.push(1); while(!q.empty()) { int now = q.front();q.pop(); std::cout << now << " "; for (auto to : edge[now]) { if(!vis[to]) { vis[to] = true; q.push(to); } } } } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); std::cin >> n >> m; for (int i = 1; i <= m; i++) { int x, y; std::cin >> x >> y; edge[x].push_back(y); } for (int i = 1; i <= n; i++) { sort(edge[i].begin(), edge[i].end()); } vis[1] = true; DFS(1); std::memset(vis, 0, sizeof(vis)); vis[1] = true; BFS(); return 0; }

__EOF__

本文作者Kdlyh
本文链接https://www.cnblogs.com/kdlyh/p/17862947.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   加固文明幻景  阅读(20)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示