HDU 1213 How Many Tables -- 并查集
2016-05-10 14:00
302 查看
How Many Tables
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 22520 Accepted Submission(s): 11206
Problem Description
Today is Ignatius' birthday. He invites a lot of friends. Now it's dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.
One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.
For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
Input
The input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked from 1 to N. Then M lines
follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.
Output
For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.
Sample Input
2 5 3 1 2 2 3 4 5 5 1 2 5
Sample Output
2 4
#include <stdio.h> #include <string.h> #include <algorithm> const int N = 1005; using namespace std; int tree ; int findroot(int x){ if(tree[x]==-1) return x; else{ int tmp=findroot(tree[x]); tree[x]=tmp; return tmp; } } int main(){ int n,m,i,j; int t; scanf("%d",&t); while(t--){ scanf("%d %d",&n,&m); for(i=1;i<=n;i++){ tree[i]=-1; } int x,y; while(m--){ scanf("%d %d",&x,&y); x=findroot(x); y=findroot(y); if(x!=y){ tree[y]=x; } } int sum=0; for(i=1;i<=n;i++){ if(tree[i]==-1) sum++; } printf("%d\n",sum); } return 0; }
相关文章推荐
- 创建线程函数的方法
- [No000091]SVN学习笔记2-TortoiseSVN Client初级操作update(获取)、commit(提交)
- Offset
- 三行代码实现iOS9新功能-SFSafariViewController
- iOS之UI学习-UITextField代理篇
- oracle的索引有几种?各有何用途?
- 【LeetCode】227. Basic Calculator
- Mac下通过Homebrew安装MySQL
- Android Studio使用
- kali rolling 的metasploit开启数据库连接!
- 虚拟总线上注册驱动
- android实现登录,Login姿势对不对?
- asp.net创建XML文件的方法小结
- JAVA面试题(1)
- 第十三章 UIGestureRecognizer and UIMenuController翻译
- Apach Web Server区别于其他应用服务器的主要特点是什么?
- 数据库中常用的操作语句
- 页面的五种布局以及嵌套
- JVM必备指南
- Magento. How to create an attribute and apply it to products