DS图—图的连通分量 答案

DS图—图的连通分量

题目描述

输入无向图顶点信息和边信息,创建图的邻接矩阵存储结构,计算图的连通分量个数。

输入

测试次数t

每组测试数据格式如下:

第一行:顶点数 顶点信息

第二行:边数

第三行开始,每行一条边信息

输出

每组测试数据输出,顶点信息和邻接矩阵信息

输出图的连通分量个数,具体输出格式见样例。

每组输出直接用空行分隔。

输入样例1

3
4 A B C D
2
A B
A C
6 V1 V2 V3 V4 V5 V6
5
V1 V2
V1 V3
V2 V4
V5 V6
V3 V5
8 1 2 3 4 5 6 7 8
5
1 2
1 3
5 6
5 7
4 8

 输出样例1

A B C D
0 1 1 0
1 0 0 0
1 0 0 0
0 0 0 0
2

V1 V2 V3 V4 V5 V6
0 1 1 0 0 0
1 0 0 1 0 0
1 0 0 0 1 0
0 1 0 0 0 0
0 0 1 0 0 1
0 0 0 0 1 0
1

1 2 3 4 5 6 7 8
0 1 1 0 0 0 0 0
1 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 1 1 0
0 0 0 0 1 0 0 0
0 0 0 0 1 0 0 0
0 0 0 1 0 0 0 0
3

#include<iostream>
using namespace std;
bool *flag = new bool;
int mitr[99][99];
int find(int pos, int num){
	flag[pos] = true;
	for(int i=0; i<num; i++){
		if(flag[i] == false && mitr[i][pos] == 1)
		find(i, num);
	}
}

int main(){
	int t;
	cin >> t;
	while(t--){
		int n;
		cin >> n;
		string *point = new string[n];
		for(int i=0; i<n; i++)
		cin >> point[i];
		int edge_n;
		cin >> edge_n;
		for(int i=0; i<n; i++){
			for(int j=0; j<n; j++)
			mitr[i][j] = 0;
		}
		string one, two;//cout<<"sad";
		int onee, twoo;
		while(edge_n--){
			cin >> one >> two;
			for(int i=0; i<n; i++){
				if(point[i] == one)
				onee = i;
				if(point[i] == two)
				twoo = i;
			}
			mitr[onee][twoo] = 1;
			mitr[twoo][onee] = 1;
		}
		//分量
		for(int i=0; i<n; i++)
		flag[i] = false;
		int count=0;
		for(int i=0; i<n; i++){
			if(flag[i] == false){
				find(i, n);
				count++;
			}
		}
		//输出
		for(int i=0; i<n; i++){
			if(i == n-1) cout << point[i];
			else cout << point[i] << " ";
		}
		cout <<endl;
		for(int i=0; i<n; i++){
			for(int j=0; j<n; j++){
				if(j == n-1) cout << mitr[i][j];
				else cout << mitr[i][j] << " ";
			}
			cout <<endl;
		} 
		cout << count << endl <<endl;
	}
	delete flag;
	return 0; 
}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Joy_szu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值