P3146 [USACO16OPEN]248 G(區間DP)
題目描述
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 NN positive integers (2≤N≤2482≤N≤248), each in the range 1…401…40. 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,每次可以合併相鄰兩個(數值範圍1-40),問序列中出現的最大數字的值最大是多少。注意合併後的數值並非加倍而是+1,例如2與2合併後的數值為3。
輸入格式
The first line of input contains NN, and the next NN lines give the sequence
of NN numbers at the start of the game.
輸出格式
Please output the largest integer Bessie can generate.
輸入輸出樣例
輸入 #1複製
4
1
1
1
2
輸出 #1
3
區間dp典型例題。注意如果區間不能完全合併也要標記,否則會T飛。
#include <bits/stdc++.h> using namespace std; int n, a[105], dp[405][405];//dp[i][j]表示第i個到第j個這一段全部合併能夠得到的最大值 int f(int l, int r) { if(dp[l][r] != 0) return dp[l][r]; for(int i = l; i < r; i++) { if(f(l, i) == -1 || f(i + 1, r) == -1) continue;//如果當前段不能全部合併 也要標記 dp[l][r] = max(dp[l][r], (f(l, i) == f(i + 1, r) ? f(l, i) + 1 : 0)); } if(dp[l][r] == 0) dp[l][r] = -1; return dp[l][r]; } int main() { cin >> n; memset(dp, 0, sizeof(dp)); for(int i = 1; i <= n; i++) { cin >> a[i]; dp[i][i] = a[i]; } int ans = 0; for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { ans = max(ans, f(i, j)); } } cout << ans << endl; return 0; }