码迷,mamicode.com
首页 > 编程语言 > 详细

匈牙利算法

时间:2015-08-02 00:46:56      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 1 /*Author :usedrose  */
 2 /*Created Time :2015/8/1 23:39:01*/
 3 /*File Name :2.cpp*/
 4 #pragma comment(linker, "/STACK:1024000000,1024000000") 
 5 #include <cstdio>
 6 #include <iostream>
 7 #include <algorithm>
 8 #include <sstream>
 9 #include <cstdlib>
10 #include <cstring>
11 #include <climits>
12 #include <vector>
13 #include <string>
14 #include <ctime>
15 #include <cmath>
16 #include <deque>
17 #include <queue>
18 #include <stack>
19 #include <set>
20 #include <map>
21 #define INF 0x3f3f3f3f
22 #define eps 1e-8
23 #define pi acos(-1.0)
24 #define MAXN 5010
25 #define MAXM 50010
26 #define OK cout << "ok" << endl;
27 #define o(a) cout << #a << " = " << a << endl
28 #define o1(a,b) cout << #a << " = " << a << "  " << #b << " = " << b << endl
29 using namespace std;
30 typedef long long LL;
31 
32 struct Edge{
33     int to, next;
34 }edge[MAXM];
35 int head[MAXM], tot;
36 
37 void init()
38 {
39     tot = 0;
40     memset(head, -1, sizeof(head));
41 }
42 
43 void addedge(int u, int v)
44 {
45     edge[tot].to = v;
46     edge[tot].next = head[u];
47     head[u] = tot++;
48 }
49 
50 int linker[MAXN];
51 bool used[MAXN];
52 int uN;
53 
54 bool dfs(int u)
55 {
56     for (int i = head[u]; i != -1; i = edge[i].next) {
57         int v = edge[i].to;
58         if (!used[v]) {
59             used[v] = true;
60             if (linker[v] == -1 || dfs(linker[v])) {
61                 linker[v] = u;
62                 return true;
63             }
64         }
65     }
66     return false;
67 }
68 
69 int hungary()
70 {
71     int res = 0;
72     memset(linker, -1, sizeof(linker));
73     for (int u = 0;u < uN;++ u) {
74         memset(used, false, sizeof(used));
75         if (dfs(u)) res++;
76     }
77     return res;
78 }
79 
80 
81 int main()
82 {
83     while (~scanf("%d", &uN)) {
84         init();
85         int a, b, c;
86         for (int i = 0;i < uN; ++ i) {
87             scanf("%d: (%d)", &a, &b);
88             for (int j = 0;j < b; ++ j) {
89                 scanf("%d", &c);
90                 addedge(a, c);
91             }
92         }
93         printf("%d\n", uN - hungary()/2);
94     }
95     return 0;
96 }
View Code

 

匈牙利算法

标签:

原文地址:http://www.cnblogs.com/usedrosee/p/4694940.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!