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
2V1 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
11 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;
}