回溯法求解流水作业调度代码
时间: 2023-12-20 20:56:43 浏览: 194
可以参考以下代码:
```
#include<stdio.h>
#define MAX 100
int process[MAX][3], best[MAX], f[100];
int n, r1, r2, mcost = 9999999;
void backtrack(int num, int sum) {
if (num == n + 1) {
if (sum < mcost) {
mcost = sum;
for (int i = 1; i <= n; i++) {
best[i] = f[i];
}
}
return;
} else {
int ok = 1;
for (int i = 1; i < num; i++) {
if (num - i >= process[i][1]) {
continue;
} else {
ok = 0;
break;
}
}
if (ok == 1) {
int t = 0;
for (int i = 1; i <= num; i++) {
t = t + process[f[i]][2];
}
if (t < mcost) {
mcost = t;
for (int i = 1; i <= num; i++) {
best[i] = f[i];
}
}
}
for (int i = 1; i <= num; i++) {
if (num - i >= process[i][1]) {
continue;
} else {
int cost = 0;
for (int j = i; j <= num - 1; j++) {
if (cost + process[f[j]][2] + process[num][2] < mcost) {
cost += process[f[j]][2];
} else {
return;
}
}
cost += process[num][2];
f[num] = num;
backtrack(num + 1, cost + sum);
f[num] = 0;
}
}
}
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d%d%d", &process[i][1], &process[i][2], &process[i][3]);
}
f[1] = 1;
backtrack(2, process[1][2]);
printf("%d\n", mcost);
for (int i = 1; i <= n; i++) {
printf("%d ", best[i]);
}
return 0;
}
```
这是一个使用回溯法求解流水作业调度的代码,输入的三个数分别表示作业编号,开始时间和作业长度。输出的第一行表示最优调度方案的总时间,第二行表示作业的调度顺序。
阅读全文