Problem Description
Nowadays, a kind of chess game called “Super Jumping! Jumping! Jumping!” is very popular in HDU. Maybe you are a good boy, and know little about this game, so I introduce it to you now。
The game can be played by two or more than two players. It consists of a chessboard(棋盘)and some chessmen(棋子), and all chessmen are marked by a positive integer or “start” or “end”. The player starts from start-point and must jumps into end-point finally. In the course of jumping, the player will visit the chessmen in the path, but everyone must jumps from one chessman to another absolutely bigger (you can assume start-point is a minimum and end-point is a maximum.). And all players cannot go backwards. One jumping can go from a chessman to next, also can go across many chessmen, and even you can straightly get to end-point from start-point. Of course you get zero point in this situation. A player is a winner if and only if he can get a bigger score according to his jumping solution. Note that your score comes from the sum of value on the chessmen in you jumping path.
Your task is to output the maximum value according to the given chessmen list.
Input
Input contains multiple test cases. Each test case is described in a line as follow: N value_1 value_2 …value_N It is guarantied that N is not more than 1000 and all value_i are in the range of 32-int. A test case starting with 0 terminates the input and this test case is not to be processed.
Output
For each case, print the maximum according to rules, and one line one case.
Sample Input
3 1 3 2
4 1 2 3 4
4 3 3 2 1
0
Sample Output
4
10
3
题目大意
现有一盘棋,从开头跳到结尾,必须从一个棋子跳到另一个更大的棋子,切不可后退。一次跳跃可以从一个棋子跳到下一个棋子,也可以跨越许多棋子,甚至可以直接从起点到终点,但是每一个棋子都有一定分数,要你求能获得的最大分数。
思路
使用动态规划。
定义一个动态数组dp[]
使用两重for循环,将两个位置上的棋子的价值进行比较。
如果后面的棋子价值大(我们看成a[i]>a[j])。则将dp[i]=max(dp[i],dp[j]+a[i]);
反之后面的棋子价值小(我们看成a[i]<a[j])。则将dp[i]=max(dp[i],a[i]);
这样经过两重循环后,我们可以得到,走到第i个旗子位置上最高得分dp[i];
将dp数组排序,得到最大值即可。
代码
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int main()
{
int n,sum,i,j;
int a[1005],dp[1005]; //dp数组用来实现动态规划
while(scanf("%d",&n)!=EOF)
{
if(n==0)
break;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
dp[i]=0;
}
dp[0]=a[0];
for(i=1;i<n;i++)
{
for(j=0;j<i;j++)
{
if(a[i]>a[j]) //如果后面的棋子大
dp[i]=max(dp[i],dp[j]+a[i]);
else //如果后面的棋子小
dp[i]=max(a[i],dp[i]);
}
}
sort(dp,dp+n); //进行排序
printf("%d\n",dp[n-1]);
}
return 0;
}