Topic background
In Xiaoming Company A, Company B red work.
Title Description
Both employees have a characteristic: a company's employees are homosexual.
A company has N employees, of which P for friends. Company B has M employees, including Q for friends. Certain friends or friends of friends.
Each pair consisting of a friend relationship with two integers (Xi, Yi), represents a number of friends were Xi, Yi. Men's number is positive, the woman's number is negative. Bob is the number 1, red number is -1.
As we all know, Xiao Ming and red are friends, then you write a program between the two companies calculated, and the little red man by Xiao Ming up to a total understanding of how much the couple can be formulated. (Including themselves)
Input Format
Line 1, four spaces separated by a positive integer N, M, P, Q.
After the P lines of two positive integers Xi, Yi.
After the Q lines of two negative integers Xi, Yi.
Output Format
Line, a positive integer representing the people by Bob and Alice know how much the couple can be up to a total of dubbed. (Including themselves)
Sample input and output
4 3 4 2 1 1 1 2 2 3 1 3 -1 -2 -3 -3
2
Description / Tips
Data for 30%, N, M <= 100, P, Q <= 200
Data for 80%, N, M <= 4000, P, Q <= 10000.
For all data, N, M <= 10000, P, Q <= 20000.
#include<iostream> #include<algorithm> #include<queue> #include<cmath> #include<cstring> #include<cstdlib> #include<cstdio> using namespace std; const int N=20005; int n,m,p,q,x,y,a1,a2; int fa1[N],fa2[N],ans1,ans2; int find1(int x){ if(fa1[x]==x) return x; return fa1[x]=find1(fa1[x]); } int find2(int x){ if(fa2[x]==x) return x; return fa2[x]=find2(fa2[x]); } int main(){ scanf("%d %d %d %d",&n,&m,&p,&q); for(int i=1;i<=n;i++) fa1[i]=i; for(int i=1;i<=m;i++) fa2[i]=i; for(int i=1;i<=p;i++){ scanf("%d %d",&x,&y); a1=find1(x); a2=find1(y); if(a1!=a2) fa1[a2]=a1; } for(int i=1;i<=q;i++){ scanf("%d %d",&x,&y); x=-x; y=-y; a1=find2(x); a2=find2(y); if(a1!=a2) fa2[a2]=a1; } for(int i=1;i<=n;i++) if(find1(i)==find1(1)) ans1++; for(int i=1;i<=m;i++) if(find2(i)==find2(1)) ans2++; printf("%d",min(ans1,ans2)); return 0; }