洛谷P3146 [USACO16OPEN]248 G 题解

原题传送门

题目描述

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 \leq N\leq 2482≤N≤248), each in the range 1 \ldots 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

说明/提示

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.

题解

看到合并就知道这题是一个区间动规

状态

d p i , j dp_{i,j} dpi,j 表示表示将序列中的第i个数合并到第j个数全部合并所能得到的最大数值

转移方程

if(dp[i][k] == dp[k+1][j] && dp[i][k])
	dp[i][j] = max(dp[i][k]+1,dp[i][j]);

即以i至k,k+1至j的区间的值如果相同,将其合并
注意当 d p i , j dp_{i,j} dpi,j为零时,不能合并

因为不一定从1到 n 的所有数字都能合并,所以答案并非 d p 1 , n dp_{1,n} dp1,n
因此我们要用一个ans变量保存最大值

if(dp[i][k] == dp[k+1][j] && dp[i][k]){
	dp[i][j] = max(dp[i][k]+1,dp[i][j]);
	ans = max(ans,dp[i][j]);
}

初始值

d p i , i dp_{i,i} dpi,i= a i a_i ai
其中 a i a_i ai表示原序列第i个数的值
因为 a i a_i ai在赋值后就没用了,所以可以直接输入 d p i , i dp_{i,i} dpi,i

代码

#include<bits/stdc++.h>
using namespace std;
const int MAX = 300;
int dp[MAX][MAX];
int ans;
int main(){
	int n;
	cin >> n;
	for(int i=1;i<=n;i++) cin >> dp[i][i];
	for(int len=2;len<=n;len++)
		for(int i=1;len+i-1<=n;i++){
			int j = i+len-1;
			for(int k=i;k<j;k++)
				if(dp[i][k] == dp[k+1][j] && dp[i][k]){
					dp[i][j] = max(dp[i][k]+1,dp[i][j]);
					ans = max(ans,dp[i][j]);
				}
		}
	cout << ans;
	return 0;
}

然后

在这里插入图片描述

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值