1
|
/*
|
2
|
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
|
3
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
4
|
of this software and associated documentation files (the "Software"), to deal
|
5
|
in the Software without restriction, including without limitation the rights
|
6
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
7
|
copies of the Software, and to permit persons to whom the Software is
|
8
|
furnished to do so, subject to the following conditions:
|
9
|
|
10
|
The above copyright notice and this permission notice shall be included in
|
11
|
all copies or substantial portions of the Software.
|
12
|
|
13
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
14
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
15
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
16
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
17
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
18
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
19
|
SOFTWARE.
|
20
|
*/
|
21
|
|
22
|
// C5 example: bipartite matching 2006-02-04
|
23
|
|
24
|
// Compile with
|
25
|
// csc /r:C5.dll BipartiteMatching.cs
|
26
|
|
27
|
using System;
|
28
|
using System.IO; // StreamReader, TextReader
|
29
|
using System.Text; // Encoding
|
30
|
using System.Text.RegularExpressions; // Regex
|
31
|
using C5;
|
32
|
using SCG = System.Collections.Generic;
|
33
|
using System.Diagnostics;
|
34
|
|
35
|
namespace BipartiteMatching
|
36
|
{
|
37
|
class MyTest
|
38
|
{
|
39
|
public static void Main(String[] args)
|
40
|
{
|
41
|
BipartiteMatching<int, char> bmi = new BipartiteMatching<int, char>(generateGraph(args));
|
42
|
HashDictionary<int, char> res = new HashDictionary<int, char>();
|
43
|
foreach (Rec<int,char> rec in bmi.Result)
|
44
|
{
|
45
|
res.Add(rec.X1, rec.X2);
|
46
|
}
|
47
|
for (int i = 0; i < args.Length; i++)
|
48
|
{
|
49
|
char c;
|
50
|
if (!res.Find(i,out c))
|
51
|
c='-';
|
52
|
Console.WriteLine(@"""{0}"" -> '{1}'", args[i], c);
|
53
|
}
|
54
|
}
|
55
|
|
56
|
static SCG.IEnumerable<Rec<int, char>> generateGraph(string[] words)
|
57
|
{
|
58
|
int i = 0;
|
59
|
foreach (string s in words)
|
60
|
{
|
61
|
foreach (char c in s)
|
62
|
{
|
63
|
yield return new Rec<int, char>(i, c);
|
64
|
}
|
65
|
i++;
|
66
|
}
|
67
|
}
|
68
|
|
69
|
/// <summary>
|
70
|
/// Implements Hopcroft and Karps algorithm for Maximum bipartite matching.
|
71
|
///
|
72
|
/// Input (to the constructor): the edges of the graph as a collection of pairs
|
73
|
/// of labels of left and right nodes.
|
74
|
///
|
75
|
/// Output (from Result property): a maximum matching as a collection of pairs
|
76
|
/// of labels of left and right nodes.
|
77
|
///
|
78
|
/// The algorithm uses natural equality on the label types to identify nodes.
|
79
|
///
|
80
|
/// </summary>
|
81
|
/// <typeparam name="TLeftLabel"></typeparam>
|
82
|
/// <typeparam name="TRightLabel"></typeparam>
|
83
|
public class BipartiteMatching<TLeftLabel, TRightLabel>
|
84
|
{
|
85
|
LeftNode[] leftNodes;
|
86
|
RightNode[] rightNodes;
|
87
|
|
88
|
class LeftNode
|
89
|
{
|
90
|
public TLeftLabel label;
|
91
|
public RightNode match;
|
92
|
public RightNode[] edges;
|
93
|
public LeftNode(TLeftLabel label, params RightNode[] edges)
|
94
|
{
|
95
|
this.label = label;
|
96
|
this.edges = (RightNode[])edges.Clone();
|
97
|
}
|
98
|
public override string ToString()
|
99
|
{
|
100
|
return String.Format(@"""{0}"" -> '{1}'", label, match);
|
101
|
}
|
102
|
}
|
103
|
class RightNode
|
104
|
{
|
105
|
public TRightLabel label;
|
106
|
public LeftNode match;
|
107
|
public LeftNode backref;
|
108
|
public LeftNode origin;
|
109
|
public RightNode(TRightLabel label)
|
110
|
{
|
111
|
this.label = label;
|
112
|
}
|
113
|
public override string ToString()
|
114
|
{
|
115
|
return String.Format(@"'{0}'", label);
|
116
|
}
|
117
|
}
|
118
|
public BipartiteMatching(SCG.IEnumerable<Rec<TLeftLabel, TRightLabel>> graph)
|
119
|
{
|
120
|
HashDictionary<TRightLabel, RightNode> rdict = new HashDictionary<TRightLabel, RightNode>();
|
121
|
HashDictionary<TLeftLabel, HashSet<RightNode>> edges = new HashDictionary<TLeftLabel, HashSet<RightNode>>();
|
122
|
HashSet<RightNode> newrnodes = new HashSet<RightNode>();
|
123
|
foreach (Rec<TLeftLabel, TRightLabel> edge in graph)
|
124
|
{
|
125
|
RightNode rnode;
|
126
|
if (!rdict.Find(edge.X2, out rnode))
|
127
|
rdict.Add(edge.X2, rnode = new RightNode(edge.X2));
|
128
|
|
129
|
HashSet<RightNode> ledges = newrnodes;
|
130
|
if (!edges.FindOrAdd(edge.X1, ref ledges))
|
131
|
newrnodes = new HashSet<RightNode>();
|
132
|
ledges.Add(rnode);
|
133
|
}
|
134
|
|
135
|
rightNodes = rdict.Values.ToArray();
|
136
|
|
137
|
leftNodes = new LeftNode[edges.Count];
|
138
|
int li = 0;
|
139
|
foreach (KeyValuePair<TLeftLabel, HashSet<RightNode>> les in edges)
|
140
|
{
|
141
|
leftNodes[li++] = new LeftNode(les.Key, les.Value.ToArray());
|
142
|
}
|
143
|
|
144
|
Compute();
|
145
|
}
|
146
|
|
147
|
public SCG.IEnumerable<Rec<TLeftLabel, TRightLabel>> Result
|
148
|
{
|
149
|
get
|
150
|
{
|
151
|
foreach (LeftNode l in leftNodes)
|
152
|
{
|
153
|
if (l.match != null)
|
154
|
{
|
155
|
yield return new Rec<TLeftLabel, TRightLabel>(l.label, l.match.label);
|
156
|
}
|
157
|
}
|
158
|
}
|
159
|
}
|
160
|
|
161
|
HashSet<RightNode> endPoints;
|
162
|
bool foundAugmentingPath;
|
163
|
|
164
|
void Compute()
|
165
|
{
|
166
|
HashSet<LeftNode> unmatchedLeftNodes = new HashSet<LeftNode>();
|
167
|
unmatchedLeftNodes.AddAll(leftNodes);
|
168
|
foundAugmentingPath = true;
|
169
|
Debug.Print("Compute start");
|
170
|
while (foundAugmentingPath)
|
171
|
{
|
172
|
Debug.Print("Start outer");
|
173
|
foundAugmentingPath = false;
|
174
|
endPoints = new HashSet<RightNode>();
|
175
|
foreach (RightNode rightNode in rightNodes)
|
176
|
rightNode.backref = null;
|
177
|
foreach (LeftNode l in unmatchedLeftNodes)
|
178
|
{
|
179
|
Debug.Print("Unmatched: {0}", l);
|
180
|
search(l, l);
|
181
|
}
|
182
|
while (!foundAugmentingPath && endPoints.Count > 0)
|
183
|
{
|
184
|
HashSet<RightNode> oldLayer = endPoints;
|
185
|
endPoints = new HashSet<RightNode>();
|
186
|
foreach (RightNode rb in oldLayer)
|
187
|
search(rb.match, rb.origin);
|
188
|
}
|
189
|
if (endPoints.Count == 0)
|
190
|
return;
|
191
|
//Flip
|
192
|
Debug.Print("Flip");
|
193
|
foreach (RightNode r in endPoints)
|
194
|
{
|
195
|
if (r.match == null && unmatchedLeftNodes.Contains(r.origin))
|
196
|
{
|
197
|
RightNode nextR = r;
|
198
|
LeftNode nextL = null;
|
199
|
while (nextR != null)
|
200
|
{
|
201
|
nextL = nextR.match = nextR.backref;
|
202
|
RightNode rSwap = nextL.match;
|
203
|
nextL.match = nextR;
|
204
|
nextR = rSwap;
|
205
|
}
|
206
|
unmatchedLeftNodes.Remove(nextL);
|
207
|
}
|
208
|
}
|
209
|
}
|
210
|
}
|
211
|
|
212
|
void search(LeftNode l, LeftNode origin)
|
213
|
{
|
214
|
foreach (RightNode r in l.edges)
|
215
|
{
|
216
|
if (r.backref == null)
|
217
|
{
|
218
|
r.backref = l;
|
219
|
r.origin = origin;
|
220
|
endPoints.Add(r);
|
221
|
if (r.match == null)
|
222
|
foundAugmentingPath = true;
|
223
|
//First round should be greedy
|
224
|
if (l == origin)
|
225
|
return;
|
226
|
}
|
227
|
}
|
228
|
}
|
229
|
}
|
230
|
}
|
231
|
}
|