跳到正文

题解

题解:P17372 [ECNA 2023] Double Up

Neverland_0219约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年11月12日
收录
2026年11月16日
更新
2026年11月21日
篇幅
约 3 分钟
获赞
1
题目
P17372

版本

  1. v1当前

0. 前言

膜拜诸位 DP 大佬 %%%

思路和水星湖老师差不多,因为代码直接用的栈(而非数组模拟),所以投上来了,具体讲一讲操作与实现,希望能帮到大家。

1. 题目分析

给定一个序列,每个数都是 22 的幂。我们可以执行两种操作:

  • ‌删除‌:移除序列中的任意一个数。

  • ‌合并‌:将两个‌相邻‌且‌相等‌的数合并为一个数,新数为原数的 22 倍。

目标是通过若干次操作,使得最终剩下的那个数尽可能大。

实际上,题目隐含的意思是,我们可以通过维护单调栈,删除多余的干扰项,让特定的子序列进行连锁合并,从而得到最大值。

2. 算法流程

step1:

遍历‌:从左到右读取序列中的每个数 a[i],记为 now。

step2:

  • 如果 now>s.top():

    执行 s.pop() (弹出栈顶),继续检查新栈顶。

  • 如果 now==s.top():

    执行 s.pop(),将 now 更新为 now *= 2(合并并翻倍),随后继续检查新栈顶。

  • 如果 now<s.top():

    直接跳出循环。将处理后的 now 压入栈,执行 s.push(now)。

step3:

统计答案‌:遍历栈中所有剩余元素,取最大值即为答案。

tip:

注意数据范围,记得开 int128。

3. 复杂度分析

时间复杂度‌:O(N)O(N)。

每个元素最多进栈一次、出栈一次,均摊复杂度为线性。

空间复杂度‌:O(N)O(N)。

栈的最大深度不超过 NN。

AC code
C++
#include<bits/stdc++.h>
using namespace std;
	__int128 a[1005];
	stack<__int128> s;
__int128 read() {
	__int128 x=0,f=1;
	char ch=getchar();
	while(ch<'0' || ch>'9') {
		if(ch=='-') {
			f=-1;
		}
		ch=getchar();
	}
	while(ch>='0' && ch<='9') {
		x=x*10+(ch-'0');
		ch=getchar();
	}
	return x*f;
}
void print(__int128 x) {
	if(x<0) {
		putchar('-');
		x=-x;
	}
	if(x>9) {
		print(x/10);
	}
	putchar(x%10+'0');
}
int main() {

	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	__int128 n,ans=-1;
	n=read();
	for(__int128 i=1; i<=n; i++) {
		a[i]=read();
	}
	for(__int128 i=1; i<=n; i++) {
		if(s.empty()) {
			s.push(a[i]);
		} else {
			__int128 now=a[i];
			while(!s.empty()) {
				if(now>s.top()) {
					s.pop();
				} else if(now==s.top()) {
					s.pop();
					now*=2;
				} else {
					break;
				}
			}
			s.push(now);
		}
	}
	while(!s.empty()) {
		ans=max(ans,s.top());
		s.pop();
	}
	print(ans);
	return 0;
}
原文