zoukankan      html  css  js  c++  java
  • 二分图之匈牙利算法模版

     1 /*
     2 匈牙利算法模版邻接表版
     3 最大匹配问题
     4 时间复杂度:O (nm)
     5 */
     6 #include <cstdio>
     7 #include <vector>
     8 #include <cstring>
     9 using namespace std;
    10 const int maxn = 505;
    11 vector<int> v[maxn];//x = v[i][j]表示i可以与x匹配
    12 int vis[maxn],match[maxn];//vis[i]防止在每次dfs中重复访问i,x = match[i]表示x当前与i匹配
    13 bool dfs(int t)
    14 {
    15     for(int i = 0; i < v[t].size(); ++i)
    16     {
    17         int x = v[t][i];
    18         if(!vis[x])
    19         {
    20             vis[x] = 1;//防止重复访问
    21             if(match[x] == -1 || dfs(match[x]))//如果x无匹配点或者x的匹配点有其他可匹配点
    22             {match[x] = t; return true; }
    23         }
    24     }
    25     return false;
    26 }
    27 int hungary(int n)
    28 {
    29     int ans = 0;
    30     for(int i = 1; i <= n; ++i)
    31     {
    32         memset(vis,0,sizeof vis);
    33         if(dfs(i)) ++ans;
    34     }
    35     return ans;
    36 }
    37 int main()
    38 {
    39     int k,n,x,y;
    40     scanf("%d%d",&k,&n);//k->可匹配对数,n->总人数
    41     for(int i = 1; i <= n; ++i)
    42         v[i].clear();
    43     memset(match,-1,sizeof match);
    44     while(k--)
    45     {
    46         scanf("%d%d",&x,&y);
    47         v[x].push_back(y);
    48     }
    49     printf("%d
    ",hungary(n));
    50     return 0;
    51 }
  • 相关阅读:
    Webpack安装及基础配置
    相机拍到了光源的灯珠图像
    面向对象特殊用法
    面向对象初始
    内置函数和必须的模块
    模块基本模式
    函数三
    函数二
    装饰器
    函数初识
  • 原文地址:https://www.cnblogs.com/qq188380780/p/7356629.html
Copyright © 2011-2022 走看看