二分图匹配(poj 1469)

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>

using namespace std ;
int const maxn = 300;
int map[maxn][maxn] , book[maxn] , use[maxn];//map用于存关系,book用于存女生的对象,use表示该女生是已经和男生配对
int n1, n2, n ,x ,t;
bool solve(int x)
{
    for(int i = 1 ; i <= n2;  i++)//枚举对象
    {
        if(map[x][i] == 1 && use[i] == 0)//当前男生情况下,判断是否存在关系,判断女生是否已经和男生配对
        {
            use[i] = 1;//如果女生没有配对,则和这个女生配对
            if(book[i] == 0 || solve(book[i]))//女生是否之前已存在对象,如果存在,则返回该女生的对象,然后递归
            {
                book[i] = x;
                return true;
            }
        }
    }
    return false;
}


int main(void)
{
    scanf("%d",&t);
    while(t --)
    {
        int ans = 0;
        memset(map,0,sizeof(map));
        memset(book,0,sizeof(book));
        scanf("%d %d",&n1 , &n2);
        for(int i = 1 ; i <= n1 ; i ++)
        {
            scanf("%d",&n);
            while(n --)
            {
                scanf("%d",&x);
                map[i][x] = 1;
            }
        }
        for(int i = 1 ; i <= n1 ; i ++)//遍历每一个男生
        {
            memset(use,0,sizeof(use));//每次都清空数据,表示,可以和任何女生配对。
            if(solve(i))
                ans ++;
        }
        if(ans == n1)
            printf("YES\n");
        else
            printf("NO\n");
    }
}

参看该博客:https://blog.csdn.net/Dark_Scope/article/details/8880547

猜你喜欢

转载自blog.csdn.net/Zenith_Habitant/article/details/83546264