forked from Pradeepsingh61/DSA_Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhungarian_algorithm.cpp
More file actions
241 lines (200 loc) · 8.17 KB
/
hungarian_algorithm.cpp
File metadata and controls
241 lines (200 loc) · 8.17 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
/**
* Hungarian Algorithm (Kuhn-Munkres Algorithm)
*
* Purpose:
* Solves the assignment problem, which is about finding the optimal assignment of n workers to n jobs,
* where each worker-job pair has an associated cost, and the goal is to minimize the total cost.
*
* Time Complexity: O(n³)
* Space Complexity: O(n²)
*
* Author: Abhi
* Date: October 13, 2025
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <limits>
class HungarianAlgorithm {
private:
std::vector<std::vector<int>> costMatrix; // Original cost matrix
std::vector<std::vector<int>> workMatrix; // Working copy of cost matrix
int size; // Size of the problem (n)
std::vector<int> labelByWorker; // Labels for workers
std::vector<int> labelByJob; // Labels for jobs
std::vector<int> minSlackWorkerByJob; // For each job, the worker that has minimum slack
std::vector<int> minSlackValueByJob; // For each job, the minimum slack value
std::vector<int> matchJobByWorker; // Which job is assigned to which worker
std::vector<int> matchWorkerByJob; // Which worker is assigned to which job
std::vector<bool> committedWorkers; // Workers committed to the search tree
// Initializes the data structures needed for the algorithm
void initialize() {
// Initialize all jobs to unmatched status
matchJobByWorker = std::vector<int>(size, -1);
matchWorkerByJob = std::vector<int>(size, -1);
committedWorkers = std::vector<bool>(size, false);
// Initialize labels: worker labels to maximum cost in their row
// job labels to 0
labelByWorker = std::vector<int>(size, 0);
labelByJob = std::vector<int>(size, 0);
for (int w = 0; w < size; w++) {
for (int j = 0; j < size; j++) {
if (costMatrix[w][j] > labelByWorker[w]) {
labelByWorker[w] = costMatrix[w][j];
}
}
}
}
// Executes an augmenting path algorithm to find an augmenting path
bool executePhase() {
// Reset committed workers
std::fill(committedWorkers.begin(), committedWorkers.end(), false);
// Reset jobs
std::vector<bool> committedJobs(size, false);
// Match all jobs to workers with zero slack
for (int j = 0; j < size; j++) {
matchWorkerByJob[j] = -1;
}
// Initialize min slack arrays
minSlackWorkerByJob = std::vector<int>(size, -1);
minSlackValueByJob = std::vector<int>(size);
// Choose the first unmatched worker
for (int w = 0; w < size; w++) {
if (matchJobByWorker[w] == -1) {
// Start the algorithm with this worker
return findAugmentingPath(w);
}
}
return false;
}
// Finds an augmenting path starting from a specific worker
bool findAugmentingPath(int initialWorker) {
committedWorkers[initialWorker] = true;
// Initialize min slack for each job
for (int j = 0; j < size; j++) {
minSlackValueByJob[j] = labelByWorker[initialWorker] + labelByJob[j] - costMatrix[initialWorker][j];
minSlackWorkerByJob[j] = initialWorker;
}
std::vector<bool> parentWorkerByCommittedJob(size, false);
std::vector<int> parentWorkerByJob(size, -1);
int worker = initialWorker;
int job = -1;
while (true) {
// Find a job with minimum slack
int minSlackJob = -1;
int minSlackValue = std::numeric_limits<int>::max();
for (int j = 0; j < size; j++) {
if (parentWorkerByCommittedJob[j]) continue;
if (minSlackValueByJob[j] < minSlackValue) {
minSlackValue = minSlackValueByJob[j];
minSlackJob = j;
}
}
// Update labels for all committed workers and jobs
if (minSlackValue > 0) {
for (int w = 0; w < size; w++) {
if (committedWorkers[w]) labelByWorker[w] -= minSlackValue;
}
for (int j = 0; j < size; j++) {
if (parentWorkerByCommittedJob[j]) {
labelByJob[j] += minSlackValue;
} else {
minSlackValueByJob[j] -= minSlackValue;
}
}
}
// Assign job to a worker
parentWorkerByJob[minSlackJob] = minSlackWorkerByJob[minSlackJob];
job = minSlackJob;
// Check if we found a job that's unassigned
if (matchWorkerByJob[job] == -1) {
break;
}
// Add the worker to the committed set
worker = matchWorkerByJob[job];
committedWorkers[worker] = true;
parentWorkerByCommittedJob[job] = true;
// Update the min slack for all jobs
for (int j = 0; j < size; j++) {
if (parentWorkerByCommittedJob[j]) continue;
int slack = labelByWorker[worker] + labelByJob[j] - costMatrix[worker][j];
if (slack < minSlackValueByJob[j]) {
minSlackValueByJob[j] = slack;
minSlackWorkerByJob[j] = worker;
}
}
}
// Update the matching by following the augmenting path
while (job != -1) {
int nextWorker = parentWorkerByJob[job];
int nextJob = matchJobByWorker[nextWorker];
matchJobByWorker[nextWorker] = job;
matchWorkerByJob[job] = nextWorker;
job = nextJob;
}
return true;
}
public:
/**
* Constructor that takes a cost matrix where costMatrix[i][j] represents
* the cost of assigning worker i to job j.
*/
HungarianAlgorithm(const std::vector<std::vector<int>>& inputMatrix) {
costMatrix = inputMatrix;
size = costMatrix.size();
// Make a working copy of the cost matrix
workMatrix = costMatrix;
// Initialize data structures
initialize();
}
/**
* Solves the assignment problem and returns the assignments and total cost.
* Returns a pair where:
* - First element is a vector of assignments (job assigned to each worker)
* - Second element is the total cost of the assignment
*/
std::pair<std::vector<int>, int> solve() {
// Main algorithm loop - keep finding augmenting paths
while (true) {
if (!executePhase()) break;
}
// Calculate the final cost and create the assignment vector
int totalCost = 0;
for (int w = 0; w < size; w++) {
int job = matchJobByWorker[w];
totalCost += costMatrix[w][job];
}
return {matchJobByWorker, totalCost};
}
};
// Utility function to print a matrix
void printMatrix(const std::vector<std::vector<int>>& matrix) {
for (const auto& row : matrix) {
for (int val : row) {
std::cout << val << "\t";
}
std::cout << std::endl;
}
}
// Example usage
int main() {
// Example cost matrix
std::vector<std::vector<int>> costMatrix = {
{250, 400, 350},
{400, 600, 350},
{200, 400, 250}
};
std::cout << "Cost Matrix:" << std::endl;
printMatrix(costMatrix);
std::cout << std::endl;
// Create and solve the assignment problem
HungarianAlgorithm ha(costMatrix);
auto [assignments, totalCost] = ha.solve();
std::cout << "Optimal Assignment:" << std::endl;
for (int i = 0; i < assignments.size(); i++) {
std::cout << "Worker " << i << " -> Job " << assignments[i] << " (Cost: " << costMatrix[i][assignments[i]] << ")" << std::endl;
}
std::cout << std::endl;
std::cout << "Total Cost: " << totalCost << std::endl;
return 0;
}