-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathassignment.cpp
More file actions
294 lines (252 loc) · 8.64 KB
/
Copy pathassignment.cpp
File metadata and controls
294 lines (252 loc) · 8.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// assignment.cpp
/*===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Vyacheslav Brover
*
* File Description:
* Assignment problem
*
*/
#undef NDEBUG
#include "common.hpp"
#include "graph.hpp"
using namespace Common_sp;
#include "version.inc"
#include "common.inc"
namespace
{
// https://en.wikipedia.org/wiki/Hungarian_algorithm
template <typename T, typename U>
using Pair = std::pair<T, U>;
template <typename T>
using Vector = std::vector<T>;
template <typename T>
using NumericLimits = std::numeric_limits<T>;
/**
* @brief Checks if b < a
*
* Sets a = min(a, b)
* @param a The first parameter to check
* @param b The second parameter to check
* @tparam The type to perform the check on
* @return true if b < a
*/
template <typename T>
constexpr bool ckmin(T& a, const T& b) {
return b < a ? a = b, true : false;
}
/**
* @brief Performs the Hungarian algorithm.
*
* Given J jobs and W workers (J <= W), computes the minimum cost to assign each
* prefix of jobs to distinct workers.
*
* @tparam T a type large enough to represent integers on the order of J *
* max(|C|)
* @param C a matrix of dimensions JxW such that C[j][w] = cost to assign j-th
* job to w-th worker (possibly negative)
*
* @return a vector of length J, with the j-th entry equaling the minimum cost
* to assign the first (j+1) jobs to distinct workers
*/
template <typename T>
Vector<T> hungarian(const Vector<Vector<T>>& C) {
const size_t/*int*/ J = /*static_cast<int>*/(C.size());
const size_t/*int*/ W = /*static_cast<int>*/(C[0].size());
assert(J <= W);
// job[w] = job assigned to w-th worker, or -1 if no job assigned
// note: a W-th worker was added for convenience
Vector<size_t/*int*/> job(W + 1, no_index /*-1*/);
Vector<T> ys(J);
Vector<T> yt(W + 1); // potentials
// -yt[W] will equal the sum of all deltas
Vector<T> answers;
const T inf = NumericLimits<T>::max();
for (size_t/*int*/ jCur = 0; jCur < J; ++jCur)
{
// assign jCur-th job
size_t/*int*/ wCur = W;
job[wCur] = jCur;
// min reduced cost over edges from Z to worker w
Vector<T> minTo(W + 1, inf);
Vector<size_t/*int*/> prev(W + 1, no_index/*-1*/); // previous worker on alternating path
Vector<bool> inZ(W + 1); // whether worker is in Z
while (job[wCur] != no_index /*-1*/) { // runs at most jCur + 1 times
inZ[wCur] = true;
const size_t/*int*/ j = job[wCur];
T delta = inf;
size_t/*int*/ wNext = 0;
for (size_t/*int*/ w = 0; w < W; ++w) {
if (!inZ[w]) {
if (ckmin(minTo[w], C[j][w] - ys[j] - yt[w]))
prev[w] = wCur;
if (ckmin(delta, minTo[w]))
wNext = w;
}
}
// delta will always be nonnegative,
// except possibly during the first time this loop runs
// if any entries of C[jCur] are negative
for (size_t/*int*/ w = 0; w <= W; ++w) {
if (inZ[w]) {
ys[job[w]] += delta;
yt[w] -= delta;
} else {
minTo[w] -= delta;
}
}
wCur = wNext;
}
// update assignments along alternating path
for (size_t /*int*/ w; wCur != W; wCur = w)
job[wCur] = job[w = prev[wCur]];
answers.push_back(-yt[W]);
}
return answers;
}
#if 0
/**
* @brief Performs a sanity check for the Hungarian algorithm.
*
* Sanity check: https://en.wikipedia.org/wiki/Hungarian_algorithm#Example
* First job (5):
* clean bathroom: Bob -> 5
* First + second jobs (9):
* clean bathroom: Bob -> 5
* sweep floors: Alice -> 4
* First + second + third jobs (15):
* clean bathroom: Alice -> 8
* sweep floors: Carol -> 4
* wash windows: Bob -> 3
*/
void sanityCheckHungarian() {
Vector<Vector<int>> costs{{8, 5, 9}, {4, 2, 4}, {7, 3, 8}};
assert((hungarian(costs) == Vector<int>{5, 9, 15}));
cerr << "Sanity check passed." << endl;
}
#endif
struct ThisApplication final : Application
{
ThisApplication ()
: Application ("Assignment problem. Print minimized or maximized total cost")
{
version = VERSION;
addPositional ("in", "File with bipartite arcs: <object1>\\t<object2>\\t<cost>");
addFlag ("max", "Maximize total cost");
}
struct AssignmentNode final : DiGraph::Node
{
const string name;
bool matched {false};
AssignmentNode (DiGraph &graph_arg,
const string &name_arg)
: DiGraph::Node (graph_arg)
, name (name_arg)
{}
};
struct CostArc final : DiGraph::Arc
{
double cost {NaN};
CostArc (AssignmentNode* start,
AssignmentNode* end,
double cost_arg)
: DiGraph::Arc (start, end)
, cost (cost_arg)
{}
bool operator< (const CostArc& other) const
{ return cost < other. cost; }
bool available () const
{ for (const bool out : {false, true})
if (static_cast <const AssignmentNode*> (node [out]) -> matched)
return false;
return true;
}
void use ()
{ for (const bool out : {false, true})
var_cast (static_cast <const AssignmentNode*> (node [out])) -> matched = true;
}
// Postcondition: !available()
};
void body () const final
{
const string fName = getArg ("in");
const double maxCoeff = getFlag ("max") ? -1.0 : 1.0;
// Naive algorithm ??
DiGraph gr; // Bipartite: from obj1 to obj2
map<string,AssignmentNode*> obj1_2node;
{
LineInput f (fName);
map<string,AssignmentNode*> obj2_2node;
while (f. nextLine ())
{
string obj1 (findSplit (f. line, '\t'));
string obj2 (findSplit (f. line, '\t'));
const double cost = maxCoeff * str2<double> (f. line);
QC_ASSERT (! isNan (cost));
trim (obj1);
QC_ASSERT (! obj1. empty ());
trim (obj2);
QC_ASSERT (! obj2. empty ());
AssignmentNode* &n1 = obj1_2node [obj1];
if (! n1)
n1 = new AssignmentNode (gr, obj1);
AssignmentNode* &n2 = obj2_2node [obj2];
if (! n2)
n2 = new AssignmentNode (gr, obj2);
if (const DiGraph::Arc* arc = n1->incident (n2, true))
var_cast (static_cast <const CostArc*> (arc)) -> cost += cost;
else
new CostArc (n1, n2, cost);
}
}
VectorPtr<CostArc> arcs; arcs. reserve (obj1_2node. size ());
for (const auto& it : obj1_2node)
for (const DiGraph::Arc* arc : it. second->arcs [true])
{
ASSERT (arc);
arcs << static_cast <const CostArc*> (arc);
}
arcs. sortPtr ();
double total = 0.0;
for (const CostArc* ca : arcs)
{
ASSERT (ca);
if (ca->available ())
{
total += ca->cost;
var_cast (ca) -> use ();
}
ASSERT (! ca->available ());
}
cout << maxCoeff * total << endl;
}
};
} // namespace
int main (int argc,
const char* argv[])
{
ThisApplication app;
return app. run (argc, argv);
}