<OJ_Sicily>Graph Problems From Data Structure Course

该博客介绍了如何解决数据结构课程中的图问题,特别是计算一个简单无向图中的连通块数量。输入包括图的顶点数和边数,输出是连通块的数目。解题方法是利用map存储节点及其相邻节点,通过遍历和标记节点来确定连通块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

输入一个简单无向图,求出图中连通块的数目。

Input

输入的第一行包含两个整数n和m,n是图的顶点数,m是边数。1<=n<=1000,0<=m<=10000。

以下m行,每行是一个数对v y,表示存在边(v,y)。顶点编号从1开始。

Output

单独一行输出连通块的数目。

题目解释:就是对于无向图,求出连通块数

解题思路:使用容器 map<int, vector<int> >,其实map的key是节点标号,vector<int> 是以key节点标号为一边的另一边节点标号。最后通过遍历标记节点,同一个连通块的标记是一样的。

#include <iostream>
#include <map>
#include <vector>
#include <stack>
#include <string.h>
using namespace std;
int class_map[1005];
int main(int argc, const char * argv[]) {
    // insert code here...
    int nodeNum, edgeNum;
    cin >> nodeNum >> edgeNum;
    map<int, vector<int> > graph;
    memset(class_map, -1, sizeof(class_map));
    for (int i = 0; i < edgeNum; i++) {
        int v,y;
        cin >> v >> y;
        graph[v].push_back(y);
        graph[y].push_back(v);
    }
    int result = 0;
    stack<int> st;
    map<int, vector<int> >::iterator it ;
    for (it = graph.begin(); it != graph.end(); it++) {
        if (class_map[it->first] == -1) {
            result++;
            st.push(it->first);
//            class_map[it->first] = result;
            while (!st.empty()) {
                int topnum = st.top();
                st.pop();
                class_map[topnum] = result;
                for (int i = 0; i < graph[topnum].size(); i++) {
                    if (class_map[graph[topnum][i]] == -1) {
                        class_map[graph[topnum][i]] = result;
                    }
                }
            }
        }
        else continue;
    }
    cout << result << endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值