连通图(STL)

连通图

Description
判断一个图是否为一个边通图
Input
n 顶点 (n<=100) 边
Output
1 表示连通
0 表示不边通
Sample Input
5
1 2
2 3
5 4
0 0
Sample Output
0
分析
这题是无向图,可以用到前面的求连通分量(DFS)(BFS)(STL)中的任意一种方法
稍加修改就行了
我用的是5.STL(邻接表)
AC代码

#include<iostream>
#include<queue>
using namespace std;
int b[105],head[10005],x,y,n,sum,tot;
struct stu
{
	int to,next;
}a[10005];
void add(int x,int y)//邻接表建立,前面都有说过
{
	tot++;
	a[tot].to=y;
	a[tot].next=head[x];
	head[x]=tot;
}
void bfs(int i)
{
	int h=0,tail=1;
	queue<int>st;//队列
	st.push(i);//入队
	b[i]=1;
	while(st.size())//判断队列是否为空
	{
	 int x=st.front(); //将队首赋值给x
	 st.pop();//队首出列
	 for(int j=head[x];j;j=a[j].next)
		if(!b[a[j].to])
		{
			b[a[j].to]=1; 
			st.push(a[j].to);//插入队列中
		}
	}
}
int main()
{
	cin>>n;
	while(cin>>x&&cin>>y)
	{
		if(x+y==0)break;
        add(x,y);add(y,x);//无向图
	}
	bfs(1);//就从一个点开始
	for(int i=1;i<=n;i++)if(b[i]==0){cout<<0;return 0;}//如果还有未被搜过的,就说明这不是连通图
	cout<<1;
}

谢谢

发布了49 篇原创文章 · 获赞 79 · 访问量 1653

猜你喜欢

转载自blog.csdn.net/weixin_45524309/article/details/103540735