DS图—图的连通分量
题目描述
输入无向图顶点信息和边信息,创建图的邻接矩阵存储结构,计算图的连通分量个数。
输入
测试次数t
每组测试数据格式如下:
第一行:顶点数 顶点信息
第二行:边数
第三行开始,每行一条边信息
输出
每组测试数据输出,顶点信息和邻接矩阵信息
输出图的连通分量个数,具体输出格式见样例。
每组输出直接用空行分隔。
输入样例:
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
输出样例:
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>
#include <vector>
#include <algorithm>
#include <list>
#include <map>
#include <queue>
using namespace std;
const int MAX_VERTICES = 100;
void processGraph(int n, int edges[MAX_VERTICES][MAX_VERTICES], string vertices[]) {
for (int i = 0; i < n; ++i) {
if (i != n - 1)
cout<<vertices[i]<<" ";
else
cout<<vertices[i]<<endl;
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (j != n - 1)
cout << edges[i][j] << " ";
else
cout << edges[i][j]<<endl;
}
}
int edgeNum = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (edges[i][j] == 1)
edgeNum++;
}
}
edgeNum /= 2;
edgeNum = n - edgeNum;
cout<<edgeNum<<endl<<endl;
}
int main() {
int T;
cin >> T;
while (T--) {
int n, m;
cin >> n;
string vertices[MAX_VERTICES];
int edges[MAX_VERTICES][MAX_VERTICES] = {0};
for (int i = 0; i < n; ++i) {
cin >> vertices[i];
}
cin >> m;
for (int i = 0; i < m; ++i) {
string u, v;
cin >> u >> v;
edges[find(vertices, vertices+n,u)-vertices][find(vertices, vertices+n,v)-vertices] = 1;
edges[find(vertices, vertices+n,v)-vertices][find(vertices, vertices+n,u)-vertices] = 1;
}
processGraph(n, edges, vertices);
}
return 0;
}