zoukankan      html  css  js  c++  java
  • Sicily connect components in undirected graph

    题目介绍:

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

    Input

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

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

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

    Sample Input
    5 3
    1 2
    1 3
    2 4
    
    Sample Output
    2

    思路:

         利用广度搜索,计算广度搜索的次数即为结果。

         具体代码如下:

     1 #include <iostream>
     2 #include <queue>
     3 using namespace std;
     4 
     5 bool path[1001][1001];
     6 bool visited[1001];
     7 
     8 int main() {
     9     int n, m;
    10     cin >> n >> m;
    11     
    12     for (int i = 0; i < m; i++) {
    13         int node1, node2;
    14         cin >> node1 >> node2;
    15         path[node1][node2] = true;
    16         path[node2][node1] = true;
    17     }
    18     
    19     for (int i = 1; i <= n; i++) {
    20         visited[i] = false;
    21     }
    22     
    23     int count = 0;
    24     int temp = n;
    25     while (temp--) {
    26         queue<int> store;
    27         for (int i = 1; i <= n; i++) {
    28             if (!visited[i]) {
    29                 store.push(i);
    30                 count++;
    31                 visited[i] = true;
    32                 break;
    33             }
    34         }
    35         
    36         while (!store.empty()) {
    37             for (int i = 1; i <= n; i++) {
    38                 if (path[store.front()][i] && !visited[i]) {
    39                     store.push(i);
    40                     visited[i] = true;
    41                 }
    42             }
    43             store.pop();
    44         }
    45     }
    46     
    47     cout << count << endl;
    48     
    49     return 0;
    50 }
  • 相关阅读:
    kafka集群partition分布原理分析
    Kafka的通讯协议
    RabbitMQ和Kafka
    深入理解kafka设计原理
    Kafka的Log存储解析
    Netty 超时机制及心跳程序实现
    Netty 实现 WebSocket 聊天功能
    Netty 实现聊天功能
    RabbitMQ在分布式系统中的应用
    Kafka文件存储机制那些事
  • 原文地址:https://www.cnblogs.com/winray/p/4152331.html
Copyright © 2011-2022 走看看