1. 程式人生 > >51nod 飛行員配對(二分圖最大匹配)

51nod 飛行員配對(二分圖最大匹配)

鄰接表存圖 匈牙利

//
//  main.cpp
//  wzazzy
//
//  Created by apple on 2018/10/23.
//  Copyright © 2018年 apple. All rights reserved.
//

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string.h>
#include<queue>
#include<stack>
#include<list>
#include<map>
#include<set>
#include<vector>

typedef long long int ll;
const int maxn =1000+10;
const int maxm=10000;
const int mod =1e9+7;
const int INF=0x3f3f3f3f;
struct Edge
{
    int to,next;
}edge[maxn];
int head[maxn],tot;
void init()
{
    tot=0;
    memset(head,-1,sizeof(head));
}
void addedge(int u,int v)
{
    edge[tot].to=v;edge[tot].next=head[u];
    head[u]=tot++;
}
int linker[maxn];
bool used[maxn];
int uN;
bool dfs(int u)
{
    for(int i=head[u];i!=-1;i=edge[i].next)
    {
        int v=edge[i].to;
        if(!used[v])
        {
            used[v]=true;
            if(linker[v]==-1||dfs(linker[v]))
            {
                linker[v]=u;
                return true;
            }
        }
    }
    return false;
}
int hungary()
{
    int res=0;
    memset(linker,-1,sizeof(linker));
    for(int u=0;u<uN;u++)
    {
        memset(used,false,sizeof(used));
        if(dfs(u)) res++;
    }
    return res;
}
int main(int argc, const char * argv[])
{
    int n,m;scanf("%d%d",&n,&m);
    int u,v;
    init();
    uN=n;
    while(scanf("%d%d",&u,&v)!=EOF&&u!=-1&&v!=-1)
    {
        u--,v--;
        addedge(u,v);
    }
    printf("%d\n",hungary());
    return 0;
}