DS图—图的连通分量

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

鷸鰥

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

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

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

打赏作者

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

抵扣说明:

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

余额充值