![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/378a36d63c7675056b31d2f3c67c6c65.png)
#include <iostream>
using namespace std;
int n;
int m;
int d;
int w[100][100] = {0};
int c[100][100] = {0};
int sum = 10000;
int currentWeight = 0;
int currentPrice = 0;
int x[100] = {0};
int best[100] = {0};
void backtrack(int i)
{
if(i >= n)
{
if(currentWeight < sum)
{
sum = currentWeight;
for(int j=0; j<n; j++)
{
best[j] = x[j];
}
}
return;
}
for(int j=0; j<m; j++)
{
currentWeight += w[i][j];
currentPrice += c[i][j];
if(currentWeight<=sum && currentPrice<=d)
{
x[i] = j;
backtrack(i+1);
}
currentWeight -= w[i][j];
currentPrice -= c[i][j];
}
}
int main()
{
cin >> n >> m >> d;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cin >> w[i][j];
}
}
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cin >> c[i][j];
}
}
backtrack(0);
bool flag = true;
for(int i=0; i<n; i++)
{
if(flag)
{
cout << best[i] + 1;
flag = false;
}
else
{
cout << " " << best[i] + 1;
}
}
cout << endl;
cout << sum << endl;
return 0;
}
可参考资料
算法分析最小重量机器设计问题
最小机器重量设计问题(回溯法-满m叉树)