#include <iostream>
#include <fstream>
#include <queue>
#include <algorithm>
using namespace std;
const int INF = 10000;
const int MAX = 50;
int c[MAX][MAX]; //价格矩阵
int w[MAX][MAX]; //重量矩阵
int bestx[MAX]; //最优解向量
int n, m, d; //部件个数,供应商数,最大总价格
class Node
{
public:
int dep; //当前层
int weight; //当前重量
int price; //当前价格
int *x; //解向量
Node(int d, int w, int p)
{
x = new int[n+1];
dep = d;
weight = w;
price = p;
}
//重量小的先出队列
bool operator < (const Node &node) const
{
return weight > node.weight;
}
};
priority_queue<Node> q;
//添加结点
void addNode(Node enode, int supplier)
{
Node now(enode.dep+1, enode.weight, enode.price);
copy(enode.x, enode.x+n+1, now.x);
now.x[now.dep] = supplier;
now.weight += w[now.dep][supplier];
now.price += c[now.dep][supplier];
q.push(now);
}
int search()
{
Node enode(0, 0, 0);
for(int j=1; j<=n; j++)
enode.x[j] = 0;
int best = INF;
while(true)
{
if(enode.dep>n)
{
if(enode.weight < best)
{
best = enode.weight;
copy(enode.x, enode.x+n+1, bestx);
break;
}
}
else
{
for(int i=1; i<=m; i++)
{
if(enode.price <= d && enode.weight <best)
addNode(enode, i);
}
}
if(q.empty())
break;
else
{
enode = q.top();
q.pop();
}
}
return best;
}
int main()
{
ifstream fin("最小重量机器设计.txt");
cout << "输入部件个数:";
fin >> n; cout << n;
cout << "\n输入供应商个数:";
fin >> m; cout << m;
cout << "\n输入最大总价格:";
fin >> d; cout << d;
cout << "\n输入价格矩阵:\n";
int i, j;
for(i=1; i<=n; i++)
{
for(j=1; j<=m; j++)
{
fin >> c[i][j];
cout << c[i][j] << " ";
}
cout << endl;
}
cout << "\n输入重量矩阵:\n";
for(i=1; i<=n; i++)
{
for(j=1; j<=m; j++)
{
fin >> w[i][j];
cout << w[i][j] << " ";
}
cout << endl;
}
cout << "\n最小重量为:" << search();
cout << "\n每个部件的供应商为:\n" ;
for(i=1; i<=n; i++)
cout << bestx[i] << " ";
cout << endl;
cout << endl;
fin.close();
return 0;
}
06-01