编程练习-动态规划(生产线问题)

来源:互联网 发布:python 廖雪峰 百度云 编辑:程序博客网 时间:2024/04/28 07:57

line_A_cost是生产线A的代价;

line_B_cost是生产线B的代价

AB_cost是从生产线A转到生产线B的代价

BA_cost是从生产线B转到生产线A的代价

代码如下:

#include <stdio.h>#include <vector>void ProductionLine(std::vector<int>& line_A_cost, std::vector<int>& line_B_cost,                    std::vector<int>& AB_cost, std::vector<int>& BA_cost) {  if (line_A_cost.size() != line_B_cost.size() ||      AB_cost.size() != BA_cost.size() ||      line_A_cost.size() - AB_cost.size() != 1 ||      line_A_cost.size() < 1) {    return;  }  std::vector<char> memo_A;  std::vector<char> memo_B;  std::vector<int> cost_A(1, line_A_cost[0]);  std::vector<int> cost_B(1, line_B_cost[0]);  int min_cost = 0;  for (int i = 1; i < line_A_cost.size(); ++i) {    if ((cost_A[i - 1] + line_A_cost[i]) < (cost_B[i - 1] + BA_cost[i - 1] + line_A_cost[i])) {      cost_A.push_back(cost_A[i - 1] + line_A_cost[i]);      memo_A.push_back('A');      printf("--%d cost A %d\n", i, cost_A[cost_A.size() - 1]);    } else {      cost_A.push_back(cost_B[i - 1] + BA_cost[i - 1] + line_A_cost[i]);      memo_A.push_back('B');      printf("%d cost A %d\n", i, cost_A[cost_A.size() - 1]);    }    if ((cost_B[i - 1] + line_B_cost[i]) < (cost_A[i - 1] + AB_cost[i - 1] + line_B_cost[i])) {      cost_B.push_back(cost_B[i - 1] + line_B_cost[i]);      memo_B.push_back('B');      printf("--%d cost B %d\n",i, cost_B[cost_B.size() - 1]);    } else {      cost_B.push_back(cost_A[i - 1] + AB_cost[i - 1] + line_B_cost[i]);      memo_B.push_back('A');      printf("%d cost B %d\n",i, cost_B[cost_B.size() - 1]);    }  }  printf("size=%zd", memo_A.size());  size_t last = cost_A.size() - 1;  std::vector<char>* current = NULL;  if (cost_A[last] > cost_B[last]) {    printf("B ");    current = &memo_B;  } else {    printf("A ");    current = &memo_A;  }  for (int j = current->size() - 1; j >= 0; --j) {    if ((*current)[j] == 'A') {      printf("A ");      current = &memo_A;    } else {      printf("B ");      current = &memo_B;    }  }}int main(int argc, char** argv) {  int A_array[] = {1, 3, 7, 2, 9};  std::vector<int> line_A_cost(A_array, A_array + sizeof(A_array) / sizeof(int));  int B_array[] = {2, 1, 3, 8, 10};  std::vector<int> line_B_cost(B_array, B_array + sizeof(B_array) / sizeof(int));  int AB_cost_array[] = {2, 3, 2, 4};  int BA_cost_array[] = {3, 1, 4, 2};  std::vector<int> AB_cost(AB_cost_array, AB_cost_array + sizeof(AB_cost_array) / sizeof(int));  std::vector<int> BA_cost(BA_cost_array, BA_cost_array + sizeof(BA_cost_array) / sizeof(int));  ProductionLine(line_A_cost, line_B_cost, AB_cost, BA_cost);}  

参考文献:

《算法导论》P193


原创粉丝点击