Question:
A retail store needs to schedule shifts for its employees over a week. Each employee has different skills and preferences, and each shift requires specific skills. The goal is to minimize the total cost (e.g., overtime, training) while ensuring all shifts are covered. Use the technique to find the optimal employee- shift assignment.
this is what i tried:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX 100
void initializeArrays(int cost[MAX][MAX], int n, int m) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cost[i][j] = 0;
}
}
}
int hungarianAlgorithm(int cost[MAX][MAX], int n, int *assignment) {
int u[MAX] = {0}, v[MAX] = {0}, p[MAX] = {0}, way[MAX] = {0};
for (int i = 1; i <= n; i++) {
int links[MAX] = {0}, minv[MAX] = {0}, used[MAX] = {0}, j0 = 0;
links[0] = i;
for (int j = 0; j <= n; j++) {
minv[j] = INT_MAX;
}
do {
used[j0] = 1;
int i0 = links[j0], delta = INT_MAX, j1;
for (int j = 1; j <= n; j++) {
if (!used[j]) {
int cur = cost[i0 - 1][j - 1] - u[i0] - v[j];
if (cur < minv[j]) {
minv[j] = cur;
way[j] = j0;
}
if (minv[j] < delta) {
delta = minv[j];
j1 = j;
}
}
}
for (int j = 0; j <= n; j++) {
if (used[j]) {
u[links[j]] += delta;
v[j] -= delta;
} else {
minv[j] -= delta;
}
}
j0 = j1;
} while (links[j0] != 0);
do {
int j1 = way[j0];
links[j0] = links[j1];
j0 = j1;
} while (j0 != 0);
for (int j = 0; j <= n; j++) {
p[links[j]] = j;
}
}
int result = -v[0];
for (int i = 1; i <= n; i++) {
assignment[p[i] - 1] = i - 1;
}
return result;
}
int main() {
int cost[MAX][MAX];
int n; // no. of employees and shifts
printf("Enter the number of employees and shifts: ");
if (scanf("%d", &n) != 1) {
printf("Failed to read the number of employees and shifts.n");
return 1;
}
if (n > MAX) {
printf("The number of employees and shifts exceeds the maximum allowed (%d).n", MAX);
return 1;
}
initializeArrays(cost, n, n);
printf("Enter the cost matrix (rows: employees, columns: shifts):n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (scanf("%d", &cost[i][j]) != 1) {
printf("Failed to read cost matrix element (%d, %d).n", i, j);
return 1;
}
}
}
int assignment[MAX];
int minCost = hungarianAlgorithm(cost, n, assignment);
printf("Optimal assignment:n");
for (int i = 0; i < n; i++) {
printf("Employee %d is assigned to shift %dn", i + 1, assignment[i] + 1);
}
printf("The minimum cost is: %dn", minCost);
return 0;
}
Output:
assignmentDAA % gcc -o shiftScheduler shiftScheduler.c
assignmentDAA % ./shiftScheduler
Enter the number of employees and shifts: 3
Enter the cost matrix (rows: employees, columns: shifts):
4 2 5
3 1 6
2 4 3
Optimal assignment:
Employee 1 is assigned to shift 3
Employee 2 is assigned to shift 2
Employee 3 is assigned to shift 1
The minimum cost is: 5
but the output isn’t correct. help me out guys idk what to do…
New contributor
zGrish is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3