二分图最大匹配【匈牙利算法】HDU-1083

本文介绍了一个典型的二分图最大匹配问题——HDU-1083题目,通过匈牙利算法实现课程与学生之间的最优匹配。文章提供了完整的C++代码示例,演示如何解决该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HDU-1083-Courses(二分图最大匹配【匈牙利算法】
解释:
p 门课程 n个人不同选
问能否一一对应上
典型二分图最大匹配!

Sample Input
2
3 3
3 1 2 3
2 1 2
1 1
3 3
2 1 3
2 1 3
1 1
Sample Output
YES
NO

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

int e[305][305];
int book[305],match[305];
int t,p,n;
int dfs(int u)
{
    for(int i=1; i<=n; i++)
    {
        if(!book[i]&&e[u][i])
        {
            book[i]=1;
            if(match[i]==0||dfs(match[i]))
            {
                match[i]=u;
                return 1;
            }
        }
    }
    return 0;
}

int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&p,&n);
        memset(e,0,sizeof(e));
        memset(match,0,sizeof(match));
        memset(book,0,sizeof(book));
        int num,x;
        for(int i=1; i<=p; i++)
        {
            scanf("%d",&num);
            for(int j=1; j<=num; j++)
            {
                scanf("%d",&x);
                e[i][x]=1;
            }
        }
        int sum=0;
        for(int i=1; i<=p; i++)
        {
            memset(book,0,sizeof(book));
            if(dfs(i))
                sum++;
        }
        if(sum==p)
        {
            printf("YES\n");
        }
        else
        {
            printf("NO\n");
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值