Sicily 4378. connect components in undirected graph

来源:互联网 发布:地脚螺栓计算软件 编辑:程序博客网 时间:2024/05/17 23:06

仍然是宽搜,只不过是多次宽搜,输出宽搜次数即可。

Run Time: 0.01sec

Run Memory: 1168KB

Code length: 1157Bytes

Submit Time: 2011-12-24 11:55:30

// Problem#: 4378// Submission#: 1120874// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/// All Copyright reserved by Informatic Lab of Sun Yat-sen University#include <iostream>#include <queue>#include <cstring>using namespace std;int main(){    int n, m;    int i, j;    queue<int> q;    int count, set;    bool visited[ 1001 ];    bool path[ 1001 ][ 1001 ];    memset( visited, false, sizeof( visited ) );    memset( path, false, sizeof( path ) );    cin >> n >> m;    while ( m-- ) {        cin >> i >> j;        path[ i ][ j ] = true;        path[ j ][ i ] = true;    }    count = 0;    set = 0;    while ( count != n ) {        for ( i = 1; i <= n; i++ ) {            if ( visited[ i ] == false ) {                q.push( i );                visited[ i ] = true;                count++;                set++;                break;            }        }        while ( !q.empty() ) {            i = q.front();            for ( j = 1; j <= n; j++ ) {                if ( path[ i ][ j ] && !visited[ j ] ) {                    q.push( j );                    visited[ j ] = true;                    count++;                }            }            q.pop();        }    }    cout << set << endl;    return 0;}                                 


 

原创粉丝点击