九度Online Judge_1526: 朋友圈
2013-07-22 10:20
351 查看
题目描述:假如已知有n个人和m对好友关系(存于数字r)。如果两个人是直接或间接的好友(好友的好友的好友...),则认为他们属于同一个朋友圈,请写程序求出这n个人里一共有多少个朋友圈。
假如:n = 5 , m = 3 , r = {{1 , 2} , {2 , 3} , {4 , 5}},表示有5个人,1和2是好友,2和3是好友,4和5是好友,则1、2、3属于一个朋友圈,4、5属于另一个朋友圈,结果为2个朋友圈。
输入:
输入包含多个测试用例,每个测试用例的第一行包含两个正整数 n、m,1=<n,m<=100000。接下来有m行,每行分别输入两个人的编号f,t(1=<f,t<=n),表示f和t是好友。 当n为0时,输入结束,该用例不被处理。
输出:
对应每个测试用例,输出在这n个人里一共有多少个朋友圈。
样例输入:
5 3
1 2
2 3
4 5
3 3
1 2
1 3
2 3
0
样例输出:
2
1
备注:典型的图的遍历问题(我用的dfs),求出连通分量个数。注意图的数据结构用邻接链表表示,用二维数组会超空间限制。
假如:n = 5 , m = 3 , r = {{1 , 2} , {2 , 3} , {4 , 5}},表示有5个人,1和2是好友,2和3是好友,4和5是好友,则1、2、3属于一个朋友圈,4、5属于另一个朋友圈,结果为2个朋友圈。
输入:
输入包含多个测试用例,每个测试用例的第一行包含两个正整数 n、m,1=<n,m<=100000。接下来有m行,每行分别输入两个人的编号f,t(1=<f,t<=n),表示f和t是好友。 当n为0时,输入结束,该用例不被处理。
输出:
对应每个测试用例,输出在这n个人里一共有多少个朋友圈。
样例输入:
5 3
1 2
2 3
4 5
3 3
1 2
1 3
2 3
0
样例输出:
2
1
备注:典型的图的遍历问题(我用的dfs),求出连通分量个数。注意图的数据结构用邻接链表表示,用二维数组会超空间限制。
#include<iostream> #include<vector> using namespace std; #define MAXNUM 100000 typedef struct person { vector<int> friends; bool visited; }Person; Person *Graph; int n,m; void dfs(int start) { //Person p = Graph[start]; Graph[start].visited = true; for(vector<int>::iterator iter = Graph[start].friends.begin();iter != Graph[start].friends.end(); iter++) { int f = *iter; //Person pf = Graph[f]; if(!Graph[f].visited) dfs(f); } } int main() { int f,t; int count; cin>>n; while(n>0) { cin>>m; Graph = new Person[n+1]; for(int i=0;i<=n;i++) { Graph[i].visited = false; } for(int i=0;i<m;i++) { cin>>f>>t; Graph[f].friends.push_back(t); Graph[t].friends.push_back(f); } count = 0; for(int i=1;i<=n;i++) { //Person p = Graph[i]; if(!Graph[i].visited) { dfs(i); count++; } } cout<<count<<endl; delete[] Graph; cin>>n; } return 0; }
相关文章推荐
- 【九度OJ】:1526 并查集 朋友圈问题
- 九度题目1526:朋友圈
- 九度 题目1526:朋友圈
- 九度oj 1526 朋友圈 并查集
- 九度 1526:朋友圈
- 九度题目1526:朋友圈 小米2013年校园招聘笔试题 并查集
- 九度 1526:朋友圈
- 九度OJ题目 1526 朋友圈 并查集
- 九度OJ 1526 朋友圈
- 【九度】题目1526:朋友圈
- 九度 1526:朋友圈(并查集)
- 九度 Online Judge 算法 刷题 题目1065:输出梯形
- 九度1526
- 题目1202 九度Online Judge
- 九度 Online Judge 算法 刷题 题目1066:字符串排序
- 九度 Online Judge 算法 刷题 题目1122:吃糖果
- 九度Online Judge程序猿求职及面试
- 九度 Online Judge 算法 刷题 题目1022:游船出租
- 九度 Online Judge 算法 刷题 题目1052:找x
- 九度 Online Judge 算法 刷题 题目1067:n的阶乘