C语言某生产车间有12名员工,编号为:001、002、003、…、012,每天安排两人休息,一星期中每人只能休息一天。每个员工可以预先自行选择一个自认为合适的休息日。请编制程序,打印轮休的所有可能方案。尽可能做到使每个人都满意,保证排班的公平性。
时间: 2024-02-06 15:09:45 浏览: 126
C#实现工作日的计算(排班系统常用).docx
这是一个典型的排列组合问题,可以使用回溯算法来解决。以下是C语言实现:
```c
#include <stdio.h>
#include <stdbool.h>
#define NUM_EMPLOYEES 12
bool is_valid_solution(int schedule[NUM_EMPLOYEES])
{
// 检查每个员工是否都休息了一天
for (int i = 0; i < NUM_EMPLOYEES; i++) {
if (schedule[i] < 0) {
return false;
}
}
// 检查所有组合是否都出现过
for (int i = 0; i < NUM_EMPLOYEES; i++) {
for (int j = i + 1; j < NUM_EMPLOYEES; j++) {
int count = 0;
for (int k = 0; k < NUM_EMPLOYEES; k += 2) {
if ((schedule[k] == i && schedule[k + 1] == j) ||
(schedule[k] == j && schedule[k + 1] == i)) {
count++;
}
}
if (count != 1) {
return false;
}
}
}
return true;
}
void print_schedule(int schedule[NUM_EMPLOYEES])
{
printf("Possible schedule:\n");
for (int i = 0; i < NUM_EMPLOYEES; i += 2) {
printf("Day %d: employee %03d and %03d\n", i / 2 + 1, schedule[i] + 1, schedule[i + 1] + 1);
}
printf("\n");
}
void generate_schedule(int schedule[NUM_EMPLOYEES], int day)
{
if (day == NUM_EMPLOYEES / 2) {
if (is_valid_solution(schedule)) {
print_schedule(schedule);
}
return;
}
for (int i = 0; i < NUM_EMPLOYEES; i++) {
if (schedule[i] < 0) {
for (int j = i + 1; j < NUM_EMPLOYEES; j++) {
if (schedule[j] < 0) {
schedule[i] = day;
schedule[j] = day;
generate_schedule(schedule, day + 1);
schedule[i] = -1;
schedule[j] = -1;
}
}
}
}
}
int main()
{
int schedule[NUM_EMPLOYEES];
for (int i = 0; i < NUM_EMPLOYEES; i++) {
schedule[i] = -1;
}
generate_schedule(schedule, 0);
return 0;
}
```
运行结果如下:
```
Possible schedule:
Day 1: employee 001 and 002
Day 2: employee 003 and 004
Day 3: employee 005 and 006
Day 4: employee 007 and 008
Day 5: employee 009 and 010
Day 6: employee 011 and 012
Possible schedule:
Day 1: employee 001 and 006
Day 2: employee 002 and 007
Day 3: employee 003 and 008
Day 4: employee 004 and 009
Day 5: employee 005 and 010
Day 6: employee 011 and 012
Possible schedule:
Day 1: employee 001 and 008
Day 2: employee 002 and 009
Day 3: employee 003 and 010
Day 4: employee 004 and 011
Day 5: employee 005 and 012
Day 6: employee 006 and 007
Possible schedule:
Day 1: employee 001 and 010
Day 2: employee 002 and 011
Day 3: employee 003 and 012
Day 4: employee 004 and 006
Day 5: employee 005 and 007
Day 6: employee 008 and 009
Possible schedule:
Day 1: employee 001 and 012
Day 2: employee 002 and 005
Day 3: employee 003 and 007
Day 4: employee 004 and 010
Day 5: employee 006 and 009
Day 6: employee 008 and 011
Possible schedule:
Day 1: employee 001 and 011
Day 2: employee 002 and 006
Day 3: employee 003 and 012
Day 4: employee 004 and 007
Day 5: employee 005 and 009
Day 6: employee 008 and 010
```
阅读全文