[Graph Theory] [Bipartite Graph Maximum Matching] Roller Coaster

 

Problem Description
RPG girls went to the playground with everyone today, and finally got on the roller coaster of their dreams. However, there are only two seats in each row of the roller coaster, and there is an unwritten rule that every girl must find a boy as a partner to sit with her. However, every girl has their own ideas. For example, Rabbit is only willing to partner with XHD or PQK, Grass is only willing to partner with linle or LL, and PrincessSnow is willing to partner with water prodigal sons or pseudoqueers. Considering the funding issue, Boss Liu decided to let only those who found the partner ride the roller coaster, and the others, hehe, just stand below and watch. Smart Acmer, can you help me figure out how many pairs can get on the roller coaster at most?
 

 

Input
The first line of the input data is three integers K , M , N, which represent the number of possible combinations, the number of girls, and the number of boys. 0<K<=1000
1<=N and M<=500. In the next K lines, each line has two numbers, which respectively indicate that the girl Ai is willing to be a partner with the boy Bj. The last 0 ends the input.
 

 

Output
For each set of data, output an integer representing the maximum number of combinations that can be taken on a roller coaster.
 

 

Sample Input
6 3 3 1 1 1 2 1 3 2 1 2 3 3 1 0
 

 

Sample Output
3
 
Idea: Use the Hungarian Algorithm to solve the maximum matching of bipartite graphs
AC code:
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int m,n;
int Map[550][550];
int vis[550];
int used[550];

bool match(int x){
  for(int i=1;i<=n;i++){
    if(!vis[i]&&Map[x][i]){
        vis[i] = 1 ;
         if (!used[i]||match(used[i])){ // This is the key: if the boy i is named and has no master, let x be his master, otherwise it is i The original owner finds another boy, and then makes x the owner of i 
            used[i]= x;
             return  true ; // match successfully 
        }
    }
  }
  return  false ; //unable to match 
}

intmain ()
{
    int k;
    while(scanf("%d",&k)!=EOF&&k){
        memset(Map,0,sizeof(Map));
        memset(used,0,sizeof(used));
        scanf("%d%d",&m,&n);
        for(int i=1;i<=k;i++){
            int a,b;
            scanf("%d%d",&a,&b);
            Map[a][b]=1;
        }
        int ans=0;
        for(int i=1;i<=m;i++){
            memset(vis,0,sizeof(vis));
            if(match(i)) ans++;
        }
        printf("%d\n",ans);
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325689662&siteId=291194637