北大 poj 1611 The Suspects

典型的并查集,贪方便少写了一行代码,结果vc和vs和一直爆栈……于是调试了很久,各种纠结啊~~~

#include <iostream> #include <queue> #include <string.h> using namespace std; const int size = 30010; int ufSet[size]; int find (const int &f) { int tmp = f; if (ufSet[tmp] != -1) { ufSet[tmp] = find (ufSet[tmp]); tmp = ufSet[tmp]; /* 一开始的时候是这样写的: ufSet[tmp] = tmp = find (ufSet[tmp]); 测试数据如下: 100 1 2 99 2 结果一直爆栈。刚开始找不出原因。当f==2的时候, fSet[tmp] == 99; 于是进到这个语句里面。就可能出现下面的情况: ufSet[99] = 99 = 99; 本来99没有父节点的,现在却指向了自己了。。。。于是 下次再ind(99)的时候,就出现无穷递归,结果就是爆栈了。 唉,。。。。。。 */ } return tmp; } void merge (const int &rootx, const int &rooty) { ufSet[rooty] = rootx; } int count () { int i, root = find(0), cnt = 1; for (i = 1; i < size; ++i) { if (root == find(i)) { ++cnt; } } return cnt; } int main() { int i, j, k, n, m, theSame; while (cin >> n >> m && n + m) { memset (ufSet, -1, sizeof(ufSet)); while (m--) { cin >> k; for (i = 0; i < k; ++i) { cin >> j; int px = find (j); if (!i) // choose the first root as the main root theSame = px; else if (theSame != px) merge (theSame, px); } } cout << count() << endl; } return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值