Sicily Connect components in undirected graph
2015-12-18 20:02
211 查看
Source:
http://soj.sysu.edu.cn/show_problem.php?pid=1002&cid=2104Description
输入一个简单无向图,求出图中连通块的数目。Sample Input
输入的第一行包含两个整数n和m,n是图的顶点数,m是边数。1<=n<=1000,0<=m<=10000。以下m行,每行是一个数对v y,表示存在边(v,y)。顶点编号从1开始。
5 3 1 2 1 3 2 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; }
相关文章推荐
- 分布式系统的本质:拆分+连接
- 分布式系统的本质:拆分+连接
- 05-2 界面跳转+屏幕旋转(图片旋转/弹框判断)
- win10+VS2013编译caffe的common.cpp错误error C4996: ‘getpid': The POSIX name for this item is deprecated.
- 分布式系统的本质:拆分+连接
- [Nginx][HttpUpstreamModule]翻译负载均衡
- 简单的计算机二维数组的元素和
- 循环遍历数组方法
- 经典算法设计:动态规划(1)
- 持续集成与灰度发布
- java中double、float类型计算精度丢失问题
- docfx组件介绍--MarkdownLite
- 前端开发-HTML5基础
- Android中px与dip,sp与dip等的转换工具类
- move组件
- gdut月赛F: 有钱的wingkou
- radios组件
- 位运算符
- HDU 1051 Wooden Sticks 贪心
- weather