POJ1611 并查集

╰半夏微凉° 2022-09-30 03:46 87阅读 0赞

这个题目是并查集的相对交简单的题目。本人第一词一次提交就ac,鸡冻呀。

将所有的组学生都union到一起,最后找到0号学生所在组的人数输出就可以了。

  1. package test;
  2. import java.util.Scanner;
  3. public class Main {
  4. static node[] stus = new node[30001];
  5. public static void main(String args[]) {
  6. Scanner cin = new Scanner(System.in);
  7. int n = cin.nextInt();
  8. int m = cin.nextInt();
  9. while (n != 0) {
  10. if (m == 0) {
  11. System.out.println(1);
  12. } else {
  13. init();// 初始化
  14. while (m > 0) {// 输入每一个组的人员id
  15. m--;
  16. int num = cin.nextInt();// 组里的人数
  17. int x = cin.nextInt();// 输入的第一个元素
  18. while (num != 1) {
  19. num--;
  20. union(x, cin.nextInt());// 本组中的每一个元素都跟x放在同一个组里
  21. }
  22. }
  23. // 查找0号学生所在组的人数
  24. int sick = stus[find(0)].childnum + 1;
  25. System.out.println(sick);
  26. }
  27. // 下一个case
  28. n = cin.nextInt();
  29. m = cin.nextInt();
  30. }
  31. }
  32. public static void init() {
  33. for (int i = 0; i < stus.length; i++) {
  34. stus[i] = new node();
  35. stus[i].childnum = 0;
  36. stus[i].parent = i;// 初始化每一个元素组成一个集合
  37. }
  38. }
  39. public static int find(int x) {// 查找元素x所在的集合,返回根节点
  40. if (stus[x].parent == x)
  41. return x;
  42. stus[x].parent = find(stus[x].parent);
  43. return stus[x].parent;
  44. }
  45. public static void union(int x, int y) {// 将两个结合合并
  46. int px = find(x);// x的父亲节点
  47. int py = find(y);// y的父亲节点
  48. if (px == py)// 如果x和y本来就是在同一个组里的,不用合并
  49. return;
  50. if (stus[px].childnum >= stus[py].childnum) {// 如果x的孩子多,则把y加到x上
  51. stus[py].parent = px;
  52. stus[px].childnum += stus[py].childnum + 1;
  53. } else {// 如果y的孩子多,则把x加到y上
  54. stus[px].parent = py;
  55. stus[py].childnum += stus[px].childnum + 1;
  56. }
  57. }
  58. // 初始化统计每个集合都只有1个人
  59. // 只要是跟X同一个集合的都连上去
  60. // 最后搜索0属于哪个集合,这个集合有多少人
  61. }
  62. class node {
  63. int parent;
  64. int childnum;
  65. }

ps:今天【2012-9-22】再看这段代码的时候,发现里面错了一点。

  1. if (m == 0) {
  2. System.out.println(n);
  3. }

当m==0的时候,应该输出的是n的数量,而不仅仅是1。看来这道题的数据量也不是很大。

-—————————————————————————-魂歌——————————————————————————

2012-09-28:

今天看了一个百度的笔试题,是集合合并的问题。http://www.yjbys.com/qiuzhizhinan/show-52701.html的第五题。

可以先将字符串编码为数字,比如说aaa对应数字1,bbb对应数字2,以此类推,然后将集合作为数字的集合,按照并查集的思路进行合并,然后再将集合还原成为字符串的集合,根据并查集的结果进行组装就形成了合并之后的结果。

发表评论

表情:
评论列表 (有 0 条评论,87人围观)

还没有评论,来说两句吧...

相关阅读

    相关 POJ1611

    这个题目是并查集的相对交简单的题目。本人第一词一次提交就ac,鸡冻呀。 将所有的组学生都union到一起,最后找到0号学生所在组的人数输出就可以了。 package