動態規劃入門G - Super Jumping! Jumping! Jumping! (有關最優子序列的一個相關題目)

題目:G - Super Jumping! Jumping! Jumping!
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.
題目的圖:https://cn.vjudge.net/contest...
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數組

大意:就是每次輸入的時候給一個數的序列,而後找裏面的遞增序列的和最大的那個,不是求最長的那個(並且這個是遞增,不是連續遞增!!);this

思路:經過一個dp數組來存到這個地方的最大可能的值。方法即將你要找個的這個位置認定爲最後一個,而後依次從最開始的位置到達這個位置,而後找對應的最大的遞增和,且每一個位置都是用dp數組來存到達這個位置的遞增最大值,全部在從最開始的位置依次日後找的時候也是用dp數組來對應比較,而不是一開始存數的那個數組;.net

代碼:code

#include<stdio.h>
#include<string.h>

int a[1005],d[1005];
int main()
{
    int n,i,j;
    while(scanf("%d",&n)!=EOF && n!=0){
        memset(d,0,sizeof(d));
        for(i=0;i<n;++i)
            scanf("%d",&a[i]);
        d[0]=a[0];
        for(i=1;i<n;++i){
            for(j=0;j<i;++j){
                if(a[j]<a[i])
                    d[i]=d[i]>(d[j]+a[i])?d[i]:(d[j]+a[i]);//這裏就是更新這個和
            }                                //以保證這個遞增和是最大的值的狀況;
            d[i]=d[i]>a[i]?d[i]:a[i];  //這個操做是爲了保證若是前面都沒有遞增的;
        }                            //則最後這個dp數組中要存的是其自身,
        int k=0;                        //用三目運算符的d[i]與其自身比較
        for(i=1;i<n;++i)            //能夠在不討論的狀況下將全部狀況總結出一個
            if(d[k]<d[i])            //共用的,固然也能夠轉換成用if進行;
            k=i;
        printf("%d\n",d[k]);
    }
    return 0;
}
相關文章
相關標籤/搜索