我出错的地方:
- 试图把树给并起来。这里鸟有编号,正确做法应该是把鸟并起来。而不是树。
思路分析
- 用并查集的办法。
- cnt[i]数组保存以i为FindFather结点的集合里面的鸟的个数,
- exist[i]表示鸟的id——i在输入的鸟的序号里面是否出现过,
- 遍历cnt数组并累加所有不为0的个数即可得知有多少棵树,
- 累加所有出现过的鸟的id的cnt的值即可得知鸟的个数
代码如下:
for(int i = 0; i < n; i++) {
scanf("%d%d", &k, &id);
exist[id] = true;
for(int j = 0; j < k-1; j++) {
scanf("%d", &temp);
Union(id, temp);
exist[temp] = true;
}
}
这是精髓
————————————————
我的代码是这么写的。只是部分正确!!!二刷时记得找出原因
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stdio.h>
#include <math.h>
#include <queue>
using namespace std;
int father[10000];