算法导论 第十五章 15-10 投资策略规划 O(n^2)

 save[j][i] = max((biggest - cost_2)*input[j][i], (save[j- 1][i] - cost_1)*input[j][i]);

#include <iostream>
#include <algorithm>

using namespace std;

void planning(double **input, int sizeI, int sizeJ, double cost_1, double cost_2);

int main() {
	double **input = new double *[5];
	for (int count = 0; count < 5; ++count) {
		input[count] = new double[5];
		for (int countJ = 0; countJ < 5; ++countJ)
			cin >> input[count][countJ];
	}
	planning(input, 5, 5, 1, 2);
}

void planning(double **input, int sizeI, int sizeJ, double cost_1, double cost_2) { //sizeI年,每年sizeJ个选择
	double **save = new double *[sizeJ];
	for (int count = 0; count < sizeJ; ++count)
		save[count] = new double[sizeI];
	double biggest = 0;								//这里的biggest和index分别记当前年数的最大值和其索引
	int index = -1;									
	for (int count = 0; count < sizeI; ++count) {
		save[0][count] = input[0][count];
		if (save[0][count] > biggest) {
			biggest = save[0][count];
			index = count;
		}
	}
	for (int countJ = 1; countJ < sizeJ; ++countJ) {
		double tempBiggest = 0;
		int tempIndex = -1;
		for (int countI = 0; countI < sizeI; ++countI) {
			if (countI != index) {
				save[countJ][countI] = max((biggest - cost_2)*input[countJ][countI], (save[countJ - 1][countI] - cost_1)*input[countJ][countI]);
			}
			else {
				save[countJ][countI] = (biggest - cost_1)*input[countJ][countI];
			}													//最大值只有两种情况,不更改投资,或者从前一年最大值更改投资
			if (save[countJ][countI] > tempBiggest) {
				tempBiggest = save[countJ][countI];
				tempIndex = countI;
			}
		}
		biggest = tempBiggest;			//这里更新
		index = tempIndex;
	}
	for (int countJ = 0; countJ < sizeJ; ++countJ) {
		for (int countI = 0; countI < sizeI; ++countI) {
			cout << save[countJ][countI] << " ";
		}
		cout << endl;
	}
}
/*
1.1 1.2 1.3 1.6 1.8
1.3 1.4 1.1 1.0 0.9
1.2 1.1 1.3 1.4 1.6
1.3 1.5 1.1 1.1 1.4
1.1 1.2 1.3 1.5 1.2
*/
/*
2 3 4 5 6
4 5 2 1 3
2 1 3 4 5
1 3 2 5 4
2 1 5 1 3
*/

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值