SWUST OJ 之 1139 Coin-row problem

There is a row of n coins whose values are some positive integers c₁, c₂,...,cn, not necessarily distinct. The goal is to pick up the maximum amount of money subject to the constraint that no two coins adjacent in the initial row can be picked up.

输入

Two lines, the first line is n (0< n <=10000), and the second line is value of coin(0< value <= 2^32).

输出

the maximum amount of money.

样例输入

6
5  1  2  10  6  2

样例输出

17

分析:

首先问题的意思是,在原始位置互不相邻的条件下,所选硬币的总值最大。设第 i 个硬币币值为 Ci,可选最大金额为 F(i)。

现在我们来考虑一般情况,对于每个硬币 i 我们有两种选择:要<--or-->不要
    要 i :那么可选硬币的金额 F( i ) = F( i - 2 ) + Ci ;
不要 i :那么可选硬币的金额 F( i ) = F( i - 1 ) ;
此时我们就得到了递推方程: F(n)= max{ F(n - 2)+ Ci , F(n - 1)}

现在我们考虑一下退出条件(特殊情况):
当 n = 0 时,有 F(0)= 0;
当 n = 1 时,有 F(1)= C1;
这样就构建一个递归函数解题。

代码:

// Text.cpp: 定义控制台应用程序的入口点。
//

#include
#include
#include
using namespace std;
int arr[10005];

int Max(int a, int b)                    //求最大值
{
	return a > b ? a : b;
}

void MaxValue(int n)
{
	arr[n] = Max(arr[n - 1], arr[n - 2] + arr[n]);
}

int main()
{
	memset(arr, 0, sizeof(arr));
	int n;
	scanf("%d", &n);
	for (int i = 1; i < n + 1; i++)
		scanf("%d", &arr[i]);

	for (int i = 2; i < n + 1; i++)    //从头开始找出每 i 个硬币的最大金额值
		MaxValue(i);

	printf("%d\r\n",arr[n]);

	return 0;
}

你可能感兴趣的:(SWUST,OJ题库,动态规划,算法练习,编程练习)