On the upcoming conference were sent
M representatives of country
A and
N representatives of country
B (
M and
N ≤ 1000). The representatives were identified with 1, 2, …,
M for country A and 1, 2, …,
N for country
B. Before the conference
K pairs of representatives were chosen. Every such pair consists of one member of delegation
A and one of delegation
B. If there exists a pair in which both member #
i of
A and member #
j of
B are included then #
i and #
j can negotiate. Everyone attending the conference was included in at least one pair. The CEO of the congress center wants to build direct telephone connections between the rooms of the delegates, so that everyone is connected with at least one representative of the other side, and every connection is made between people that can negotiate. The CEO also wants to minimize the amount of telephone connections. Write a program which given
M,
N,
K and
K pairs of representatives, finds the minimum number of needed connections.
The first line of the input contains
M,
N and
K. The following
K lines contain the choosen pairs in the form of two integers
p
1 and
p
2,
p
1 is member of
A and
p
2 is member of
B.
The output should contain the minimum number of needed telephone connections.
input | output |
---|---|
3 2 4 1 1 2 1 3 1 3 2 | 3 |
#include<iostream>
#include<cstring>
using namespace std;
const int N=1000+5;
bool a[N][N],v[N];
int pre[N];
int n,m,k;
bool dfs(int x){
for(int i=1;i<=m;i++)
if(!v[i]&&a[x][i]){
v[i]=1;
if(!pre[i]||dfs(pre[i])){
pre[i]=x;return 1;
}
}return 0;
}
int main(){
scanf("%d%d%d",&n,&m,&k);
for(int i=0;i<k;i++){
int b,c;
scanf("%d %d",&b,&c);
a[b][c]=1;
}
int ans=0;
for(int i=1;i<=n;i++){
memset(v,0,sizeof(v));
if(dfs(i))ans++;
}
printf("%d",n+m-ans);
}