The best solutions:
The 1th will arrange the tasks: 2
The 2th will arrange the tasks: 1
The 3th will arrange the tasks: 3
The 4th will arrange the tasks: 4
The total cost is: 13
The corresponding codes:
这其实是书本上的代码,我主要对于第32行的代码感觉有点问题,书上对应的是:d[j] = 0;而我认为是的是d[i] =0; 我修改了一下,以后发现结果是一摸一样的,这也解答了我之前的一个疑惑,其实对于回溯而言,真正起到回到上一个结点的代码是递归函数的调用本身,而这个地方起到回到之前真正作用的是worker对应的取值,只要这个改变成之前原来的样子就ok了。
# include <stdio.h>
# include <string.h>
# include <queue>
# include <vector>
using namespace std;
# define INF 99999
# define MAXN 21
int n = 4;
int c[MAXN][MAXN] = {
{0},{0,9,2,7,8},{0,6,4,3,7},{0,5,8,1,8},{0,7,6,9,4}};
int x[MAXN];
int cost = 0;
int bestx[MAXN];
int mincost = INF;
bool worker[MAXN];
void dfs(int i)
{
if (i > n){
if (cost < mincost){
mincost = cost;
for (int j = 1; j <= n; j++){
bestx[j] = x[j];
}
}
}else{
for (int j = 1; j <= n; j++){
if(!worker[j]){
worker[j] = true;
x[i] = j;
cost += c[i][j];
dfs(i+1);
worker[j] = false;
x[i] = 0;
cost -= c[i][j];
}
}
}
}
int main() {
memset(worker, 0, sizeof(worker));
dfs(1);
printf("The best solutions:\n");
for (int k =1 ; k <= n; k++) {
printf(" The %dth will arrange the tasks: %d\n", k, bestx[k]) ;
}
printf(" The total cost is: %d\n", mincost);
}