1611:The Suspects
2016-01-04 00:00
841 查看
百练上全局题号是1611,POJ题号貌似是613.现在还搞不清楚全局题号是什么。
这是一道最近简单的并查集问题,注意的一点就是,合并的时候一定要把小序号作为父母节点,这样,所有跟0相关的节点,最后都会指向0节点。代码自带缩短路径。
这是一道最近简单的并查集问题,注意的一点就是,合并的时候一定要把小序号作为父母节点,这样,所有跟0相关的节点,最后都会指向0节点。代码自带缩短路径。
#include <iostream> #include <stdio.h> using namespace std; #define MAX_SIZE 30000+10 int p[MAX_SIZE]; int Init_Array(int n) { for (int i = 0; i < n; i++){ p[i] = i; } return 0; } int Find_parent(int i) { if (p[i] != i){ p[i] = Find_parent(p[i]); } return p[i]; } bool Unit_ij(int i, int j) { int temp; int Pi = Find_parent(i); int Pj = Find_parent(j); if (Pi != Pj){ if(Pj > Pi){ temp = Pi; Pi = Pj; Pj = temp; } p[Pi] = Pj; } return true; } int main() { int n,m; //m record the number of teams int num; //num record the number of teammates int first; //the first number of the teammates int next; //the next number of the teammates int count; //the suspects while(cin>>n && n != 0){ cin>>m; Init_Array(n); count = 0; for(int i = 0;i < m;i++) { cin>>num; cin>>first; for(int j = 1;j < num;j++) { cin>>next; Unit_ij(first,next); } } for(int i = 0;i < n;i++) { if(Find_parent(i) == 0) count++; } cout<<count<<endl; } return 0; }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析