并查集
总结:
1.求两次并查集可以用一个数组来使用, 一次并查集后更新fa[]数组即可;
2.求两个值的是否是一样的祖先时,用find(),不用fa[]数组判断,有可能其中某个值的路径没被压缩;
3.a,b公司都有可能是男或女
#include<bits/stdc++.h> using namespace std; int n, m, q, p, a, b, s1, s2; int fa[10005]; int find(int x) { if(fa[x] == x) return x; return fa[x] = find(fa[x]); } void hb(int x, int y) { if(find(x) != find(y)) fa[find(y)] = find(x); } int main() { cin >> n >> m >> p >> q; for(int i = 1; i <= n; i++) fa[i] = i; for(int i = 1; i <= p; i++) { cin >> a >> b; if(a < 0) a = -a, b = -b; hb(a, b); } for(int i = 1; i <= n; i++) if(find(i) == find(1)) s1++; for(int i = 1; i <= m; i++) fa[i] = i; for(int i = 1; i <= q; i++) { cin >> a >> b; if(a < 0) a = -a, b = -b; hb(a, b); } for(int i = 1; i <= m; i++) if(find(i) == find(1)) s2++; cout << min(s1, s2); return 0; }