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
题目大意:
给定一串数字 , 求出其一个递增子序列,并使其和最大。
注:子序列与子串的区别:子序列不一定是连续的 , 但是子串一定是连续的。
例如:给定一个数串 :1 3 2 4 6 2
其递增子序列的最大和为 (1 + 3 + 4 + 6) = 14
解题思路:
利用数组dp[i] 来记录到第 i (包含i)个数字的递增子序列和。
继续以上述例子为例:num : 1 3 2 4 6 2 (下标从0开始)
显然,dp[0] = num[0] = 1;
求dp[1] 时 ,num[1] 之前只有一个 num[0]
比较num[0] 和 num[1] 的大小 , 若num[0] > num[1] , 则 dp[1] = num[1]
若num[0] < num[1], 符合递增条件,则dp[1] = dp[0] + num[1];
求dp[2]时 , 依次比较 num[2] 与 num[0]、num[1]的关系;
首先 num[2] 和 num[0] 比较, 若num[0] > num[2] , 则 dp[2] = num[2]
若num[0] < num[2], 符合递增条件,则dp[2] = dp[0] + num[2];
注:这里的dp[2]都只是一个暂存值。
再比较num[2] 和 num[1] , 若num[1] > num[2] , 则 dp[2] = num[2]
若num[1] < num[2], 符合递增条件,则dp[2] = dp[1] + num[2];
注:上面之所以说dp[2]是暂存值是因为,num[2]之前有两个数,
这里他就有可能有多个不同的值,
根据题目要求dp[2]取多个值中的最大值。
接下来,dp[3] ….dp[5]也都这样计算。
代码:
#include <cstdio>
#include <cstring>
using namespace std;
int path[1010];
int dp[1010];
int main(){
int n , i , j , maxsum = 0;
while(scanf("%d",&n) != EOF){
if( n == 0)
break;
maxsum = 0;
memset(path , 0 , sizeof(path));
memset(dp , 0 , sizeof(dp));
for(i = 0 ; i < n ; i ++)
scanf("%d",&path[i]);
dp[0] = path[0];
maxsum = dp[0];
for(i = 1 ; i < n ; i ++){
for(j = 0 ; j < i ; j ++){
if(path[i] > path[j])
dp[i] = dp[i] > dp[j] + path[i] ? dp[i] : dp[j] + path[i];
if(path[i] < path[j])
dp[i] = dp[i] > path[i] ? dp[i] : path[i];
}
if(dp[i] > maxsum)
maxsum = dp[i];
}
printf("%d\n" , maxsum);
}
return 0;
}