【题目来源】
https://www.acwing.com/problem/content/description/3590/
【问题描述】
给定一个无向图和其中的所有边,判断这个图是否所有顶点都是连通的。
【输入格式】
输入包含若干组数据。
每组数据第一行包含两个整数 n 和 m,表示无向图的点和边数。
接下来 m 行,每行包含两个整数 x,y,表示点 x 和点 y 相连。
点的编号从 1 到 n。
图中可能存在重边和自环。
【输出格式】
每组数据输出一行,一个结果,如果所有顶点都是连通的,输出 YES,否则输出 NO。
【数据范围】
输入最多包含 10 组数据。
1≤n≤1000,
1≤m≤5000,
1≤x, y≤n
【链式前向星解析】
本题解法需要对图进行DFS,所以需要存图。
在图论算法实现中,常使用C++标准库STL自带的vector来模拟邻接表存图。详见:
https://blog.csdn.net/hnjzsyjyj/article/details/101233779
https://blog.csdn.net/hnjzsyjyj/article/details/101233485
https://blog.csdn.net/hnjzsyjyj/article/details/101233249
但是,在算法竞赛中,使用C++标准库STL自带的vector来模拟邻接表存图的方法,对某些复杂问题会超时。此外,在处理网络流问题中的构建反向边等操作时会麻烦一些。据此,可引入链式前向星这种用数组模拟邻接表存图的优秀数据结构。
本质上,链式前向星是以存储边的方式来存储图。换句话说,链式前向星是一种特殊的边集数组。
链式前向星特别适合用来优化 SPFA、DFS、BFS。
● 链式前向星:https://blog.csdn.net/hnjzsyjyj/article/details/139369904
val[idx]:存储编号为 idx 的边的值
e[idx]:存储编号为 idx 的结点的值
ne[idx]:存储编号为 idx 的结点指向的结点的编号
h[a]:存储头结点 a 指向的结点的编号
在上述约定下,则有:
● 链式前向星的核心代码如下:
void add(int a,int b) {
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
如果是有权图,需多设置一个数组 val[] 存储权值。有权图的链式前向星的核心代码如下:
void add(int a,int b,int w) {
val[idx]=w,e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
● 基于链式前向星的深度优先搜索(DFS)的核心代码如下:
void dfs(int u) {
cout<<u<<" ";
st[u]=true;
for(int i=h[u]; ~i; i=ne[i]) { //~i; equivalent to i!=-1;
int j=e[i];
if(!st[j]) {
dfs(j);
}
}
}
● 基于链式前向星的深度优先搜索(BFS)的核心代码如下:
void bfs(int u) {
queue<int>q;
st[u]=true;
q.push(u);
while(!q.empty()) {
int t=q.front();
q.pop();
cout<<t<<" ";
for(int i=h[t]; ~i; i=ne[i]) { //~i; equivalent to i!=-1;
int j=e[i];
if(!st[j]) {
q.push(j);
st[j]=true; //need to be flagged immediately after being queued
}
}
}
}
【本题算法代码】
/* 链式前向星存图
val[idx]:存储编号为 idx 的边的值
e[idx]:存储编号为 idx 的结点的值
ne[idx]:存储编号为 idx 的结点指向的结点的编号
h[a]:存储头结点 a 指向的结点的编号
*/
#include <bits/stdc++.h>
using namespace std;
const int maxn=1005;
const int maxm=5005;
int e[maxm<<1],ne[maxm<<1],h[maxn],idx;
bool st[maxn];
// Undirected edges are special directed edges, open double
// int e[maxm<<1],ne[maxm<<1],h[maxn],val[maxm<<1],idx;
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;
for(int i=h[u]; i!=-1; i=ne[i]) { //~i; equivalent to i!=-1;
int j=e[i];
if(!st[j]) dfs(j);
}
}
int main() {
while(cin>>n>>m) {
memset(st,false,sizeof(st));
memset(h,-1,sizeof(h));
idx=0;
while(m--) {
int a,b;
scanf("%d%d",&a,&b);
add(a,b),add(b,a);
}
dfs(1);
bool flag=true;
for(int i=1; i<=n; i++)
if(!st[i]){
flag=false;
break;
}
if(flag) printf("YES\n");
else printf("NO\n");
}
return 0;
}
/*
in:
4 3
1 2
2 3
3 2
3 2
1 2
2 3
out:
NO
YES
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/126474608
https://blog.csdn.net/hnjzsyjyj/article/details/126455868
https://blog.csdn.net/weixin_46503238/article/details/120476387
https://www.acwing.com/solution/content/124095/