HDU- Problem-2063过山车 ——匈牙利算法的简单应用

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=2063

过山车
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 40614 Accepted Submission(s): 17123

Problem Description
RPG girls今天和大家一起去游乐场玩,终于可以坐上梦寐以求的过山车了。可是,过山车的每一排只有两个座位,而且还有条不成文的规矩,就是每个女生必须找个个男生做partner和她同坐。但是,每个女孩都有各自的想法,举个例子把,Rabbit只愿意和XHD或PQK做partner,Grass只愿意和linle或LL做partner,PrincessSnow愿意和水域浪子或伪酷儿做partner。考虑到经费问题,boss刘决定只让找到partner的人去坐过山车,其他的人,嘿嘿,就站在下面看着吧。聪明的Acmer,你可以帮忙算算最多有多少对组合可以坐上过山车吗?

Input
输入数据的第一行是三个整数K , M , N,分别表示可能的组合数目,女生的人数,男生的人数。0<K<=1000
1<=N 和M<=500.接下来的K行,每行有两个数,分别表示女生Ai愿意和男生Bj做partner。最后一个0结束输入。

Output
对于每组数据,输出一个整数,表示可以坐上过山车的最多组合数。

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

Sample Output
3

此题就是匈牙利算法的简单应用,匈牙利算法的详解我已经发布在了我的博客中,还请读者自行翻阅,此题我们就不稍加解释了,直接上AC代码。

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<algorithm>
#include<cmath>
#include<string>
#include<memory.h>

using namespace std;

const int maxn=550;
int m,n,t;
bool line[maxn][maxn];//图
bool used[maxn]; //判断此时的男生有没有被配对
int nex[maxn]; //存储此时的与男生配对的女生
int temp1,temp2;
bool Find(int x)
{
    for(int i=1;i<=m;i++)
    {
        if(line[x][i]&&!used[i])
        {
            used[i]=true;
            if(nex[i]==0||Find(nex[i]))//判断是否名花有主或者能否让出空位,递归去判断。
            {
                nex[i]=x;//到这了才是真的配对成功,在上面的used始终是个标记。
                return true;
            }
        }
    }
    return false;
}
int match()
{
    int sum=0;
    for(int i=1;i<=n;i++)
    {
        memset(used,false,sizeof(used));
        if(Find(i))sum++;//遍历每一个女生,寻找最大增广路径。
    }
    return sum;
}
int main()
{
    while(cin>>t&&t)
    {
        cin>>n>>m;
        memset(line,false,sizeof(line));
        memset(nex,0,sizeof(nex));
        while(t--)
        {
            cin>>temp1>>temp2;
            line[temp1][temp2]=true;
        }
        cout<<match()<<endl;
    }
}

猜你喜欢

转载自blog.csdn.net/hzf0701/article/details/107392849
今日推荐