1. 程式人生 > 實用技巧 >5-4 最小重量機器設計問題 (20分)

5-4 最小重量機器設計問題 (20分)

設某一機器由n個部件組成,每一種部件都可以從m個不同的供應商處購得。設wij​​是從供應商j 處購得的部件i的重量,cij​​是相應的價格。 試設計一個演算法,給出總價格不超過d的最小重量機器設計。

輸入格式:

第一行有3 個正整數n ,m和d, 0<n<30, 0<m<30, 接下來的2n 行,每行n個數。前n行是c,後n行是w。

輸出格式:

輸出計算出的最小重量,以及每個部件的供應商

輸入樣例:

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 

程式碼:

#include <bits/stdc++.h>
using
namespace std; int n; // n個部件 int m; // 每個部件m種選擇 int MaxPrice; // 允許的最高價格 int weight[40][40]; // weight[i][j] 表示 商家j 提供的 部件i 的重量 int price[40][40]; // price[i][j] 表示 商家j 提供的 部件i 的價格 int MinWeight=999999; int BestRecord[40]; //最好路徑,哪個部件用了哪些商家的貨 int PreRecord[40]; // Present Record,當前方案所選擇的路徑 , PreRecord[i]表示第i個部件選的商家
int PrePrice = 0; // 搜尋時,當前總價格 int PreWeight = 0; // 搜尋時,當前總重量 void GetRecord() { for(int i=1;i<=n;i++) { BestRecord[i] = PreRecord[i]; } } void search(int dep) // 第dep個部件該選哪個商家 { if(dep>n) { //遞迴到葉子節點,說明當前價格PrePrice < MaxPrice 產生了一組解 if(PreWeight < MinWeight ) { MinWeight
= PreWeight ; GetRecord(); // 獲取路徑 } return ; } for(int i=1;i<=m;i++) // 分別對用m個商家的部件的情況進行討論 { PrePrice = PrePrice + price[dep][i]; PreWeight = PreWeight + weight[dep][i]; PreRecord[dep] = i; if( PreWeight < MinWeight && PrePrice <= MaxPrice ) search(dep+1); PrePrice = PrePrice - price[dep][i]; PreWeight = PreWeight - weight[dep][i]; } return ; } int main() { cin>>n>>m>>MaxPrice; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ cin>>price[i][j]; } } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ cin>>weight[i][j]; } } search(1); cout<<MinWeight<<endl; for(int i=1;i<=n;i++) { cout<<BestRecord[i]<<" "; } return 0; }