Sicily Connect components in undirected graph

来源:互联网 发布:暗黑3 网络延迟 编辑:程序博客网 时间:2024/06/06 01:19

Source:

http://soj.sysu.edu.cn/show_problem.php?pid=1002&cid=2104

Description

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

Sample Input

输入的第一行包含两个整数n和m,n是图的顶点数,m是边数。1<=n<=1000,0<=m<=10000。
以下m行,每行是一个数对v y,表示存在边(v,y)。顶点编号从1开始。

5 31 21 32 4

Sample Output

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

2

Caution:

水题,bfs之。

示例代码:

#include<iostream>#include<algorithm>#include<cstring>#include<queue>#include <vector>using namespace std;int n, m, v, y,ans;vector<int> g[10001];int vis[10001];void init(){    cin >> n >> m;    while (m--)    {        cin >> v >> y;        g[v].push_back(y);        g[y].push_back(v);    }}void bfs(int s){    vis[s] = 1;    queue<int> q;    q.push(s);    while (!q.empty())    {        int u = q.front();        for (int i = 0; i < g[u].size(); ++i)            if (!vis[g[u][i]])            {                q.push(g[u][i]);                vis[g[u][i]] = 1;            }        q.pop();    }}void solve(){    for (int i = 1; i <= n; ++i)    {        if (vis[i] != 1)        {            ++ans;            bfs(i);        }    }    cout << ans << endl;}int main(){    init();    solve();    return 0;}
1 0
原创粉丝点击