连通分量问题分析

5 篇文章 0 订阅
5 篇文章 0 订阅

今天拿起来了小白书,开始仔细的过一过。
连通分量问题:
编写一个程序,输入QQ的好友关系,判断从指定任务出发是否能通过盆友链抵达目标任务。
(题目实在懒得写,拍了张照片)

在这里插入图片描述

关于这个问题,其实不难,是一个简单的无向图**(不一定连通哦)**,查找两个点之间是否连通,书本上给了一种解法,然后我把它打出来,发现觉得些许有些麻烦。

测试用例:
10 9
0 1
0 2
3 4
5 7
5 6
6 7
6 8
7 8
8 9
3
0 1
5 9
1 3

书上代码:

#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
static const int MAX = 100000;
static const int NIL = -1;

int n;
vector<int> G[MAX];
int color[MAX];

void dfs(int r,int c) {
	stack<int> S;
	S.push(r);
	color[r] = c;

	while(!S.empty()) {
		int u = S.top();
		S.pop();
		for(int i = 0; i<G[u].size(); i++) {
			if(color[G[u][i]] == NIL) {
				color[G[u][i]] = c;
				S.push(G[u][i]);
			}
		}
	}
}

void assignColor() {
	int id = 1;
	for(int i=0; i<n; i++) color[i] = NIL;
	
	//这里其实就是一个深度搜索,搜索所有连通着的点。
	for(int u = 0; u<n; u++) {
		if(color[u] == NIL) dfs(u,id++);
	}
}


int main() {
	int s,t,m,q;

	cin>>n>>m;
	
	int num = n;

	for(int i = 0; i<m; i++) {
		cin>>s>>t;
		G[s].push_back(t);
		G[t].push_back(s);
	}

	assignColor(); 

	cin>>q;

	for(int i = 0; i<q; i++) {
		cin>>s>>t;
		if(color[s] == color[t])
			cout<<"yes"<<endl;
		else
			cout<<"no"<<endl;
	}
}

写完之后,发现自己以前写过相关问题,于是就把另一种写了些试一试。
代码如下:

#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
static const int MAX = 100000;
static const int NIL = -1;

int n;

//方法2 
int Gro[100];

int findGroup(int x)
{
	if(x==Gro[x])	
		return x;
	return findGroup(Gro[x]);
}
int main() {
	int s,t,m,q;

	cin>>n>>m;
	
	int num = n;
	for(int i=1;i<=n;i++)
		Gro[i] = i;

	for(int i = 0; i<m; i++) {
		cin>>s>>t;
		int x = findGroup(s);
		int y = findGroup(t);
		
		if(x != y)
		{
			num--;
			Gro[x] = Gro[y];
		}
	}

	cin>>q;

	for(int i = 0; i<q; i++) {
		cin>>s>>t;
		if(color[s] == color[t])
		int x = findGroup(s);
		int y = findGroup(t);
		
		if(x != y)
			cout<<"no"<<endl;
		else 
			cout<<"yes"<<endl;
	}
}

只写了一个函数,自认为比上面dfs简单一点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值