zoukankan      html  css  js  c++  java
  • 匈牙利算法

    匈牙利算法,用于二分图最大匹配,时间复杂度为O(NM)

    话不多说,直接上代码

    #include<iostream>
    #include<cstdio>
    #include<cstdlib>
    #include<cstring>
    #include<algorithm>
    #include<cmath>
    using namespace std;
    int n,m,ans,e[101][101],book[101],match[101];
    
    bool dfs(int u)
    {
        int i;
        for(i=1;i<=n;i++)
        {
            if(e[u][i]==1 && book[i]==0)
            {
                book[i]=1;
                if(match[i]==0 || dfs(match[i]))
                {
                    match[i]=u;
                    match[u]=i;
                    return true;
                }
            }
        }
        return false;
    }
    
    int main()
    {
        int x,y,i;
        scanf("%d%d",&n,&m);
        for(i=1;i<=m;i++)
        {
            scanf("%d%d",&x,&y);
            e[x][y]=1;
            e[y][x]=1;
        }
        memset(match,0,sizeof(match));
        for(i=1;i<=n;i++)
        {
            memset(book,0,sizeof(book));
            if(dfs(i)) ans++;
        }
        printf("%d",ans);
        return 0;
    }
  • 相关阅读:
    HTML初体验
    out传值
    函数
    冒泡排序
    数组
    异常语句
    类 string math
    for 穷举 迭代
    HTML JavaScript及运算符
    HTML 格式与布局
  • 原文地址:https://www.cnblogs.com/llllllpppppp/p/7295065.html
Copyright © 2011-2022 走看看