题解:P17372 [ECNA 2023] Double Up

· · 题解

0. 前言

膜拜诸位 DP 大佬 %%%

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

1. 题目分析

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

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

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

2. 算法流程

step1:

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

step2:

step3:

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

tip:

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

3. 复杂度分析

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

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

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

栈的最大深度不超过 N 。

::::info[AC code]

#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;
}

::::