20201003008陆启康第五章算法实验报告
1. 请用回溯法的方法分析“最小重量机器设计问题”
本题中有了n个零部件,m个供应商,每个供应商给的零件的重量和价格,故建立深度为n,层数为m的解空间树。要求总价格不超过d的最小重量机器设计。初始化设置当前价值和当前重量为0。再设置一个最小值min
代码:
#include<iostream>
using namespace std;
int n,m,d;
int array1[100][100];
int array2[100][100];
int cw=0;
int cp=0;
int bestw=1000000;
int x[100];
int x1[100];
void machine(int t){
if(t>=n){
if(cw<bestw){
bestw=cw;
for(int i=0;i<n;i++){
x1[i]=x[i];
}
}
return;
}
for(int i=0;i<m;i++){
cp+=array1[t][i];
cw+=array2[t][i];
x[t]=i;
if(cp<=d && cw <=bestw){
machine(t+1);
}
cp-=array1[t][i];
cw-=array2[t][i];
}
}
int main()
{
cin >> n >> m >> d;
memset(x1,0,sizeof(x1));
memset(x,0,sizeof(x));
memset(array1,0,sizeof(array1));
memset(array2,0,sizeof(array2));
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin >> array1[i][j];
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin >> array2[i][j];
}
}
machine(0);
cout << bestw << endl;
for(int i=0;i<n;i++){
cout << x1[i]+1 << " ";
}
return 0;
}
1.1 说明“最小重量机器设计问题"的解空间
解空间为:{{1,3,1},{1,3,2},{1,3,3}}
1.2 说明 “最小重量机器设计问题"的解空间树
本题中有了n个零部件,m个供应商,每个供应商给的零件的重量和价格,故建立深度为n,层数为m的解空间树。
1.3 在遍历解空间树的过程中,每个结点的状态值是什么
在遍历空间树的过程中,每个结点的状态值是当前的总价格和当前的总重量。
2. 你对回溯算法的理解
回溯法是一种相当常见且实用的算法。