二分图之匈牙利算法模版
生活随笔
收集整理的這篇文章主要介紹了
二分图之匈牙利算法模版
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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\n",hungary(n));
50 return 0;
51 }
?
轉載于:https://www.cnblogs.com/qq188380780/p/7356629.html
總結
以上是生活随笔為你收集整理的二分图之匈牙利算法模版的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux常用命令大全(转)好东西要分享
- 下一篇: Hessian 源码简单分析