【USACO16OPEN】248 動態規劃

題目描述

Bessie likes downloading games to play on her cell phone, even though she doesfind the small touch screen rather cumbersome to use with her large hooves.

She is particularly intrigued by the current game she is playing.The game starts with a sequence of positive integers (), each in the range . In one move, Bessie cantake two adjacent numbers with equal values and replace them a singlenumber of value one greater (e.g., she might replace two adjacent 7swith an 8). The goal is to maximize the value of the largest numberpresent in the sequence at the end of the game. Please help Bessiescore as highly as possible!

給定一個1*n的地圖,在裏面玩2048,每次可以合併相鄰兩個,問最大能合出多少

輸入輸出格式

輸入格式:
The first line of input contains , and the next lines give the sequence

of numbers at the start of the game.

輸出格式:
Please output the largest integer Bessie can generate.

輸入輸出樣例

輸入樣例#1:
4
1
1
1
2
輸出樣例#1:
3
說明

In this example shown here, Bessie first merges the second and third 1s to

obtain the sequence 1 2 2, and then she merges the 2s into a 3. Note that it is

not optimal to join the first two 1s.

正解:動態規劃,類似於石子合併。遇到dp還是要多思考,多想想以前做過的題。
f[i][j] 爲將i,j合併後得到的最大的數f[i][j]=max(f[i][k]+1,f[i][j])(f[i][k]==f[k+1][j])
時間複雜度O(n)

代碼:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int f[250][250],a[250];
int n,maxx,k,ans=-1;
int main()
{
    int i,tmp,j,t;
    scanf("%d",&n);
    for (i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
        f[i][i]=a[i];
    }
    for (i=n-1;i>=1;i--)
        for (j=i+1;j<=n;j++)
            for (k=i;k<=j-1;k++)
            {
                if (f[i][k]==f[k+1][j])
                    f[i][j]=max(f[k+1][j]+1,f[i][j]);
                ans=max(ans,f[i][j]);
            }
    printf("%d",ans);
}
發佈了79 篇原創文章 · 獲贊 32 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章