当前位置:网站首页>(笔记整理未完成)【图论】图的遍历
(笔记整理未完成)【图论】图的遍历
2022-08-02 06:01:00 【gzkeylucky】
知识点
小K 喜欢翻看洛谷博客获取知识。每篇文章可能会有若干个(也有可能没有)参考文献的链接指向别的博客文章。小K 求知欲旺盛,如果他看了某篇文章,那么他一定会去看这篇文章的参考文献(如果他之前已经看过这篇参考文献的话就不用再看它了)。
假设洛谷博客里面一共有 篇文章(编号为 1 到 n)以及
条参考文献引用关系。目前小 K 已经打开了编号为 1 的一篇文章,请帮助小 K 设计一种方法,使小 K 可以不重复、不遗漏的看完所有他能看到的文章。
这边是已经整理好的参考文献关系图,其中,文献 X → Y 表示文章 X 有参考文献 Y。不保证编号为 1 的文章没有被其他文章引用。
请对这个图分别进行 DFS 和 BFS,并输出遍历结果。如果有很多篇文章可以参阅,请先看编号较小的那篇(因此你可能需要先排序)。
输入格式
共 m+1 行,第 1 行为 2 个数,n 和 m,分别表示一共有 篇文章(编号为 1 到 n)以及
条参考文献引用关系。
接下来 m 行,每行有两个整数 X,Y表示文章 X 有参考文献 Y。
输出格式
共 2 行。 第一行为 DFS 遍历结果,第二行为 BFS 遍历结果。
输入输出样例
输入 #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
已AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn=1e7+5;
int n,m,a,b;
bool visit[maxn];
int head[maxn],Next[maxn],tot,temp[maxn];
struct Edge
{
int from,to;
}edge[maxn];
inline int read()
{
int x=0,f=1;
char c=getchar();
while(c<'0'||c>'9')
{
if(c=='-') f=-1;
c=getchar();
}
while(c>='0'&&c<='9')
{
x=(x<<3)+(x<<1)+(c^48);
c=getchar();
}
return x*f;
}
bool cmp(Edge x,Edge y)
{
if(x.from==y.from) return x.to > y.to;
else return x.from<y.from;
}
inline void add(int u,int v) //建图
{
edge[++tot].to=v;
Next[tot]=head[u];
head[u]=tot;
}
inline void dfs(int x)
{
printf("%d ",x);
visit[x]=true;
for(int j=head[x];j;j=Next[j])
{
if(!visit[edge[j].to])
dfs(edge[j].to);
}
}
void bfs(int x)
{
memset(visit,false,sizeof(visit)); //不要忘记数组清零!!!
queue <int> q;
q.push(1);
visit[1]=true;
while(!q.empty())
{
int z=q.front();
printf("%d ",z);
q.pop();
for(int j=head[z];j;j=Next[j])
{
int y=edge[j].to;
if(visit[y]==false)
{
q.push(edge[j].to);
visit[edge[j].to]=true;
}
}
}
}
int main()
{
n=read();m=read();
for(int i=1;i<=m;++i)
{
edge[i].from=read();
edge[i].to=read();
}
sort(edge+1,edge+m+1,cmp);
for(int i=1;i<=m;++i)
{
add(edge[i].from,edge[i].to);
}
dfs(1);
cout<<endl;
bfs(1);
return 0;
}
边栏推荐
猜你喜欢
随机推荐
APP special test: traffic test
The international top conference OSDI included Taobao system papers for the first time, and the device-cloud collaborative intelligence was recommended by the keynote speech of the conference
[Cartoon] 2021 full score programmer behavior comparison table (latest version)
有人开源全凭“为爱发电”,有人却用开源“搞到了钱”
[数据集][VOC]男女数据集voc格式6188张
MySQL database video tutorial from beginner to proficient
In-depth analysis of the initialization of member variables and local variables
2022年8月计划,着重ue4视频教程
MySQL Advanced - MVCC (ultra-detailed finishing)
Technology empowers Lhasa's "lungs", Huawei helps Lalu Wetland Smart Management to protect lucid waters and lush mountains
npm、cnpm的安装
Launch Space on-premises deployment (local) Beta!
Ue after video tutorial first
nacos源码启动找不到istio包
ue先视频教程后深入
科技赋能拉萨之“肺”,华为助力拉鲁湿地智慧管理守护绿水青山
pointer arithmetic in c language
HCIP 第一天
Node installation and configuration (node-v12.20.2-x64 ) and introduction to node version switching
Nacos安装详细过程