本文主要是介绍1118. Birds in Forest并查集,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1118. Birds in Forest
Hash会误将这个当成两棵树,而出现问题。
例如:
① 1 2 3
② 4 5 6
③ 3 7 4
#include<iostream>
#include<set>
using namespace std;
const int maxn = 10010;
set<int> st;
int n, m, k;
int fa[maxn], cnt[maxn];
int findFather(int x) {int a = x;while(x != fa[x])x = fa[x];while(a != fa[a]) {int z = a;a = fa[a];fa[z] = x;}return x;
}
void Union(int a, int b) {int faA = findFather(a);int faB = findFather(b);if(faA != faB) fa[faA] = faB;
}
bool exist[maxn];
int main() {scanf("%d", &n);for(int i = 1; i <= maxn; i++) fa[i] = i;int id, temp;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;}} int numBirds = 0;for(int i = 1; i <= maxn; i++) {if(exist[i] == true) {numBirds++;int q=findFather(i);st.insert(q);}}printf("%d %d\n", st.size(), numBirds);scanf("%d", &m);int x, y;for(int i = 0; i < m; i++) {scanf("%d%d", &x, &y);printf("%s\n", (findFather(x) == findFather(y)) ? "Yes" : "No");}return 0;
}
这篇关于1118. Birds in Forest并查集的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!