题目链接:1118 Birds in Forest
原本以为自己代码写得很丑,特别是对每组中头节点的处理时,总感觉自己错了,但是看了好多人写的答案,发现自己代码还算是写的比较漂亮的。注意最后的并集操作啊,就是u
附上一个并查集写的很有意思的博客哈哈哈【算法与数据结构】—— 并查集
这次的bug又de了我个把小时…就是因为注释那里,可恶的PAT测试平台啊!!!为什么不告诉我错在哪里!!!
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 7;
int pre[maxn];
int f(int node)
{if (node == pre[node])return node;pre[node] = f(pre[node]);return pre[node];
}
void u(int a, int b)
{int fa = f(a);int fb = f(b);if (fa != fb)pre[fa] = fb;
}int main()
{int birdnum = 0;for (int i = 1; i <= maxn; i++)pre[i] = i;int n;cin >> n;for (int i = 1; i <= n; i++){int m;cin >> m;int fa;cin >> fa;if (fa > birdnum)birdnum = fa;for (int j = 2; j <= m; j++){int t;cin >> t;if (t> birdnum)birdnum = t;//if (pre[t] != t)//pre[fa] = f(t);//else//pre[t] = f(fa);u(fa, t);//两者并不等价,但如果换成是pre[pre[fa]]=f(t),就等价了}}set<int>s;for (int i = 1; i <= birdnum; i++)s.insert(f(i));cout << s.size() << ' ' << birdnum << endl;int q;cin >> q;for (int i = 0; i < q; i++){int a1, a2;cin >> a1 >> a2;if (pre[a1] == pre[a2])cout << "Yes\n";elsecout << "No\n";}
}