HDU 2063 过山车(二分图匹配邻接矩阵+邻接表 匈牙利算法 O(VE))

版权声明:get busy living...or get busy dying https://blog.csdn.net/qq_41444888/article/details/89047378

二分图最大匹配匈牙利算法,算是最简单的二分图入门算法了

通过递归实现匹配信息的不断更新

讲解博客:https://blog.csdn.net/acmman/article/details/38421239

题目链接:https://vjudge.net/problem/HDU-2063

邻接矩阵+邻接表

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#define ll long long
#define mod 1000000007
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 505;
int boy[maxn];//记录被选着的编号
bool vis[maxn];
int head[maxn];
int cnt;
void init()
{
    memset(head, -1, sizeof(head));
    cnt = 0;
}
int n, m, k;
struct node
{
    int to, next;
}e[maxn*maxn];
void addedge(int u, int v)
{
    e[cnt].to = v;
    e[cnt].next = head[u];
    head[u] = cnt ++;
}
int dfs(int u)
{
//    for(int i = 1; i <= m; i ++)//枚举被选者
//    {
//        if(link[x][i] && ! vis[i])
//        {
//            vis[i] = 1;
//            if(boy[i] == 0 || dfs(boy[i]))
//            {
//                boy[i] = x;
//                return 1;
//            }
//        }
//    }
    for(int i = head[u]; ~i; i = e[i].next)
    {
        int v = e[i].to;
        if(! vis[v])
        {
            vis[v] = 1;
            if(boy[v] == 0 || dfs(boy[v]))
            {
                boy[v] = 1;
                return 1;
            }
        }
    }
    return 0;
}
int main()
{
    while(scanf("%d", &k) != EOF && k)
    {
        scanf("%d%d", &n, &m);
        init();
        memset(boy, 0, sizeof(boy));
        memset(vis, 0, sizeof(vis));
        int u, v;
        for(int i = 1; i <= k; i ++)
        {
            scanf("%d%d", &u, &v);
            addedge(u, v);
        }
        int ans = 0;
        for(int i = 1; i <= n; i ++)
        {
            memset(vis, 0, sizeof(vis));
            if(dfs(i)) ans ++;
        }
        printf("%d\n", ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41444888/article/details/89047378