问题描述:
设某一机器由n个部件组成,每一种部件都可以从m个不同的供应商处购得。设是从供应商j处购得的部件i的重量,是相应的价格。
试设计一个优先队列式分支限界法,给出总价格不超过d的最小重量机器设计。
代码
#include
<iostream>
#include
<queue>
using namespace std
;
int n
;
int m
;
int d
;
int bestw
;
int **c
= NULL
;
int **w
= NULL
;
class Node
{
public:
int weight
;
int val
;
int source
;
int level
;
int priority
;
Node
*father
;
};
Node
*leaf
;
void InPut(){
cout
<<"请分别输入部件个数,供应商个数,及最大的总价格(n m d):"<<endl
;
cin
>>n
>>m
>>d
;
w
= new int*[n
+1];
c
= new int *[n
+1];
for(int i
= 1;i
<= n
; i
++)
{
w
[i
] = new int [m
+1];
c
[i
] = new int [m
+1];
}
leaf
= NULL
;
cout
<<"请输入各个部件在各个供应商处购买的价格:"<<endl
;
for(int i
= 1 ; i
<= n
; i
++)
for (int j
= 1 ; j
<= m
; j
++)
cin
>>c
[i
][j
];
cout
<<"请输入各个部件在各个供应商处购买的重量:"<<endl
;
for(int i
=1;i
<=n
;i
++)
for(int j
=1;j
<=m
;j
++)
cin
>>w
[i
][j
];
}
bool operator
<(Node a
,Node b
)
{
if(a
.priority
== b
.priority
)return a
.level
<b
.level
;
return a
.priority
> b
.priority
;
}
void QueuePriority(Node a
)
{
int currentMinW
;
a
.priority
=a
.val
;
for(int i
=a
.level
+1 ; i
<=n
; i
++)
{
currentMinW
= INT_MAX
;
for(int j
=1;j
<=m
;j
++)
{
currentMinW
= currentMinW
<w
[i
][j
]?currentMinW
:w
[i
][j
];
}
a
.priority
+=currentMinW
;
}
}
bool
constraint(Node
* pNode
,int i
){
if(pNode
->val
+c
[pNode
->level
+1][i
] <=d
||pNode
->weight
+w
[pNode
->level
+1][i
] <= bestw
){
return true;
}
return false;
}
Node
createNode(int level
,Node
* father
,int source
,int val
,int weight
){
Node newNode
;
newNode
.level
= level
;
newNode
.father
= father
;
newNode
.source
= source
;
newNode
.val
=val
;
newNode
.weight
= weight
;
return newNode
;
}
void MinWeightMachine()
{
int i
,j
;
bestw
= INT_MAX
;
Node initial
;
initial
=createNode(0,NULL
,0,0,0);
QueuePriority(initial
);
priority_queue
<Node> heap
;
heap
.push(initial
);
while(!heap
.empty())
{
Node
*pNode
= new Node(heap
.top());
heap
.pop();
if(pNode
->level
== n
)
{
if(pNode
->weight
<bestw
)
{
bestw
= pNode
-> weight
;
leaf
= pNode
;
}
}
else
{
for(i
=1;i
<=m
;i
++)
{
if(constraint(pNode
,i
))
{
Node newNode
;
newNode
=createNode(pNode
->level
+1,pNode
,i
,pNode
->val
+ c
[pNode
->level
+1][i
],pNode
->weight
+ w
[pNode
->level
+1][i
]);
QueuePriority(newNode
);
heap
.push(newNode
);
}
}
}
}
}
void OutPut(){
cout
<<"求得的最小重量为:"<<bestw
<<endl
;
int *result
= new int[n
+1];
for(int i
=n
;i
>=1;i
--)
{
result
[i
] = leaf
->source
;
leaf
= leaf
->father
;
}
cout
<<"各个部件的供应商分别为:"<<endl
;
for(int i
=1;i
<=n
;i
++)
cout
<<result
[i
]<<" ";
cout
<<endl
;
}
int main()
{
InPut();
MinWeightMachine();
OutPut();
}
测试样例
输入 请分别输入,部件个数,供应商个数,及最大的总价格: 3 3 4 请依次输入各个部件在各个供应商处购买的价格: 1 2 3 3 2 1 2 2 2 请依次输入各个部件在各个供应商处购买的重量: 1 2 3 3 2 1 2 2 2
输出 求得的最小重量为:4 各个部件的供应商分别为: 1 3 1