题目大意:

  有一个人要过生日了,请他的朋友来吃饭,但是他的朋友互相认识的才能坐在一起,朋友的编号从1 ~ n,输入的两个数代表着这两个人互相认识(如果1和2认识,2和3认识,那么1和3也就认识了)。问需要多少桌子。

思路:

  并查集的基础题目,pre数组存的是父节点的值,root数组代表是否为根节点。最后统计根节点的数量就可以了~~~~~

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <algorithm>
using namespace std;
const int MAXN = 1e3 + ;
int pre[MAXN];
bool root[MAXN]; int Find(int x)
{
int r = x;
while(pre[r] != r)
{
r = pre[r];
}
int i = x,j;
while(pre[i] != r) //路径压缩
{
j = i;
i = pre[i];
pre[j] = r;
}
return r;
} void mix(int a,int b)
{
int x = Find(a);
int y = Find(b);
if(x > y)
{
pre[x] = y;
}
if(x < y)
{
pre[y] = x;
}
} int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int M,N;
for(int i = ; i <= MAXN; i++)
{
pre[i] = i;
root[i] = false;
}
scanf("%d%d",&M,&N);
while(N--)
{
int a,b;
scanf("%d%d",&a,&b);
mix(a,b);
}
for(int i = ; i <= M; i++)
{
if(pre[i] == i)
root[i] = true;
}
int ans = ;
for(int i = ; i <= M; i++)
{
if(root[i]) ans ++;
}
printf("%d\n",ans);
}
return ;
}

最新文章

  1. 自定义 Activity 的 标题栏 TitleBar
  2. Windows Azure Virtual Network (7) 设置Azure Virtual Machine固定公网IP (Virtual IP Address, VIP) (2)
  3. 【BZOJ-3832】Rally 拓扑序 + 线段树 (神思路题!)
  4. VS重新生成后仍然执行旧代码
  5. cocos2d-x 3.2 listview scorllview 等容器在小米华为等部分手机显示泛白解决
  6. EF 示例
  7. 从一个例子中体会React的基本面
  8. 关于typedef的使用方法
  9. 关于 Apple Metal API 的一些想法
  10. SpringAop学习
  11. iOS开发中的那些小技巧
  12. CSS水平、垂直居中小结
  13. android——fragment详解
  14. 【转】IntentService的原理及使用
  15. git使用教程及github远程仓库管理
  16. 测试与发布(Alpha版本)
  17. UltraEdit激活方法
  18. 使用java命令重启tomcat
  19. 安卓开发笔记(二十四):手把手教你一步步集成腾讯X5内核(Tencent TBS X5)
  20. eq

热门文章

  1. 【bzoj4998】星球联盟 LCT+并查集
  2. JavaScript正则表达式大全
  3. innodb_force_recovery
  4. __cdecl,__stdcall,__fastcall,__pascal,__thiscall 的区别
  5. JRE集成到Tomcat
  6. 状压dp的题目列表 (一)
  7. All in One到”分布式“迁移过程中的坑
  8. 在Idea中使用Eclipse编译器
  9. Matlab xpC启动盘
  10. bzoj1499: [NOI2005]瑰丽华尔兹&amp;&amp;codevs1748 单调队列优化dp