HDU-1087 Super Jumping! Jumping! Jumping!(DP)

来源:互联网 发布:js实战教程 编辑:程序博客网 时间:2024/04/20 07:23

xProblem 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,把之前运算得出的结果用同样的运算方法得出下一个结果,这样就可以得出一个dp数组。

本题是最长上升子序列的题,例如一个例子 4 1 4 2 4,开始瞎想了一下,结果得出一个运算方式:
code:

for(int i=2;i<n+1;i++){    if(a[i]>a[i-1])        dp[i]=max(dp[i-1]+a[i],a[i]);    else        dp[i]=max(dp[i-1],a[i]);}

结果为5 ,不为 7 ,把似最大子序列的方式搬过来了,然后结果可想而知。

所以后面看了下别人的解题报告,最主要的是要 每次求出的都是以i结尾的最大上升子序列,如上例,
dp[2]应该为5吧,但dp[3]应该为3,因为虽然4>1+2,但是不是以2结尾的。每次算出一个dp,再以一个变量作为记录最大值的,最后用于输出答案。
code:

#include <iostream>using namespace std;int main(){    int n;    while(cin>>n,n>0)    {        int a[n+1],dp[n+1];        for(int i=1;i<n+1;i++)        {            cin>>a[i];            dp[i]=a[i];        }        a[0]=dp[0]=0;        int t=0,ans=0;  //t是临时变量 ,ans是答案         for(int i=2;i<n+1;i++)        {             t=0;   //初始化              for(int j=1;j<=i;j++){                if(a[j]<a[i]){  //用i之前的每一个a[j]与a[i]作比较,选出以前做的dp里最大的,最后用于和a[i]相加得出相应的dp[i]                     t=max(t,dp[j]);                }             }             dp[i]=a[i]+t;  //如果前面都大于a[i]的话,t就是0咯              ans=max(ans,dp[i]);         }        cout<<ans<<endl;    }    return 0; }
原创粉丝点击