并查集
2016-03-06 20:39
225 查看
import java.util.Scanner; public class T1012 { static int[] Tree = new int[1001]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n, m,count; while ((n = sc.nextInt()) != 0) { count =0 ; m = sc.nextInt(); for (int i = 1; i < n+1; i++) { Tree[i] = -1; } for (int i = 0; i < m; i++) { int a = sc.nextInt(); int b = sc.nextInt(); a = findRoot(a); b = findRoot(b); if(a!=b)Tree[a] = b; } for(int i = 1 ; i < n+1 ; i++){ if(Tree[i]==-1)count++; } System.out.println(count-1); } } static int findRoot(int x) { if (Tree[x] == -1)return x; else { Tree[x] = findRoot(Tree[x]); return Tree[x]; } } }
相关文章推荐
- 总结
- 批判性思维——Asking The Right Questions
- 20135302魏静静Linux内核分析第二周学习总结
- 第一周学习总结
- layers框架
- php关闭浏览器,程序继续执行
- 直接给字符指针赋字符串
- 通过进程ID获取进程名
- 1201 18岁生日
- 【VS开发】recv函数函数返回值说明(特别有利于工程调试)
- NYOJ 题目860 又见01背包 (特别版01背包)
- 1045. 快速排序(25)
- (java) Kth Smallest Element in a BST
- vector容器的三种遍历方法
- 【java学习记录】spilt小结
- Linux内核分析二:一个简单的时间片轮转多道程序内核代码
- 自我介绍
- yii框架-依赖注入
- 背包
- HDU 3873 Invade the Mars dijkstra最短路