算法——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.

翻译

给定一排n个硬币,其面值均为正整数c1,c2,...,cn,这些数并不一定两两相同。请问如何选择硬币,使得在其原始位置互不相邻的条件下,所选的总金额最大。 

输入

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

代码 

#include<iostream>
using namespace std;
int a[10000];
int main(){
	int n;
	cin>>n;
	a[0]=0;
	for(int i = 1; i <= n; i++){
		cin>>a[i];
		a[i] = max(a[i-2] + a[i],a[i-1]);
		
	}
	cout<<a[n]<<endl;
	return 0;
}

 

思路 

 符合初始条件的递归方程:

画图会更加的明白:

把图上的过程看懂了,这道题就会变得特别简单。 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章