最新消息:点击查看大S的省钱秘笈

POJ 1611 The Suspects C语言版

POJ题解 Slyar 103浏览 0评论

文章作者:姜南(Slyar) 文章来源:Slyar Home (www.slyar.com) 转载请注明,谢谢合作。

第一次写并查集

Description

Severe acute respiratory syndrome (SARS), an atypical pneumonia of unknown aetiology, was recognized as a global threat in mid-March 2003. To minimize transmission to others, the best strategy is to separate the suspects from others.
In the Not-Spreading-Your-Sickness University (NSYSU), there are many student groups. Students in the same group intercommunicate with each other frequently, and a student may join several groups. To prevent the possible transmissions of SARS, the NSYSU collects the member lists of all student groups, and makes the following rule in their standard operation procedure (SOP).
Once a member in a group is a suspect, all members in the group are suspects.
However, they find that it is not easy to identify all the suspects when a student is recognized as a suspect. Your job is to write a program which finds all the suspects.

Input

The input file contains several cases. Each test case begins with two integers n and m in a line, where n is the number of students, and m is the number of groups. You may assume that 0 < n <= 30000 and 0 <= m <= 500. Every student is numbered by a unique integer between 0 and n−1, and initially student 0 is recognized as a suspect in all the cases. This line is followed by m member lists of the groups, one line per group. Each line begins with an integer k by itself representing the number of members in the group. Following the number of members, there are k integers representing the students in this group. All the integers in a line are separated by at least one space.
A case with n = 0 and m = 0 indicates the end of the input, and need not be processed.

Output

For each case, output the number of suspects in one line.

Sample Input

100 4
2 1 2
5 10 13 11 12 14
2 0 1
2 99 2
200 2
1 5
5 1 2 3 4 5
1 0
0 0

Sample Output

4
1
1

Slyar:说下题目大意。一共有n个学生(编号0 至 n-1),m个组,一个学生可以同时加入不同的组。现在有一种传染病,如果一个学生被感染,那么和他同组的学生都会被感染。现在已知0号学生被感染,问一共有多少个人被感染。

恩,就是基本的并查集操作。首先将每个学生都初始化为一个集合,然后将同组的学生合并,设置一个数组num[]来记录每个集合中元素的个数,最后只要输出0号学生所在集合中元素的个数即可。

第一次是16MS AC的,后来看到说可以通过压缩路径来优化,就是在查找到祖先节点之后将路径上所有它的子孙节点都连接到它上面,这样树的高度就大大降低了...使用之后果然,0MS AC...

后来发现对于根节点来说,father[]本身就可以记录节点数目,只不过值是负的。所以又写了一个没有sun[]的版本。不过貌似负数运算比较慢,交了3次都是16MS...

转载请注明:Slyar Home » POJ 1611 The Suspects C语言版

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (4)

  1. @ 编译器不同,运行时间不同,得到的时间不同。时间是浮云,不在乎...=_=
    Slyar6年前 (2010-11-11)回复
  2. 大牛,我拿你程序在POJ测了一下,是10ms,而非0ms。。。
    匿名6年前 (2010-11-11)回复
  3. 有些地方不是很懂,能不能一下你的QQ号,我想请教一下你,我的QQ493712874
    gongzhi7年前 (2010-05-08)回复