Urall-1109(二分图的最大匹配 匈牙利算法)

来源:互联网 发布:东方财富股票交易软件 编辑:程序博客网 时间:2024/06/15 07:53
Conference
Time Limit:500MS     Memory Limit:65536KB   
Description
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.
Input
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 p1 and p2, p1 is member of A and p2 is member of B.
Output
The output should contain the minimum number of needed telephone connections.
Sample Input
input output
3 2 4
1 1
2 1
3 1
3 2

3

即将到来的会议A国派出M个代表,B国派出N个代表 (M and N <= 1000).A国的代表编号为1, 2, ..., M ;B国的代表编号为1, 2, ..., N .开会前,要选择K对代表。每一对代表必须一个是A国的,一个是B国的。A国的成员i与B国的成员j就可结对(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.???)每一个参加会议的代表至少包含在其中一对中。大会的CEO想在代表的房间建立直接的电话联系。所以每个人都至少跟对方的一个人联系起来。每一个电话联系是在有结对关系的人们之间建立的(every connection is made between people that can negotiate.???如何翻译)。CEO想建立最少的电话联系。
input:
首行给定M,N,K。以下K行为结对的代表P1,P2。P1是A国的成员,P2是B国的成员。

最大独立集数 = 节点数 – 最大匹配数。 就是要加的电话连接数量

#include<iostream>#include<stdio.h>#include<string.h>using namespace std;int n,m,k;int v[1001],pre[1001],f[1001][1001];bool dfs(int x){for(int i=1;i<=f[x][0];i++)if(!v[f[x][i]]){v[f[x][i]]=1;if(pre[f[x][i]]==0||dfs(pre[f[x][i]])){pre[f[x][i]]=x;return 1;}}return 0;}int main(){int x,y,i;scanf("%d%d%d",&n,&m,&k);for(i=1;i<=n;i++)f[i][0]=0;memset(pre,0,sizeof(pre));for(i=1;i<=k;i++){scanf("%d%d",&x,&y);f[x][++f[x][0]]=y;}int ans=0;for(i=1;i<=n;i++)//匈牙利算法{memset(v,0,sizeof(v));if(dfs(i)) ans++;}printf("%d\n",m+n-ans);}


0 0
原创粉丝点击