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
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;
}