跳到正文

题解

B4280 [蓝桥杯青少年组国赛 2023] 数学实验 题解

Lexore_约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年3月14日
更新
2026年3月14日
篇幅
约 2 分钟
题目
B4280

版本

  1. v1当前

问题理解

  • 有一个正整数序列,每次可以合并相邻且相等的两个数,合并后变成一个比原来大 1 的数。 重复这个过程,直到无法合并为止。 不同的合并顺序可能导致最终的最大数不同,我们要找出可能得到的最大数。

关键思路

这个问题其实是一个经典的“合并相邻相同数”问题,可以用贪心 + 栈的方法解决。

核心思想:

  • 从左到右扫描数列,用一个栈来保存当前无法合并的数。
  • 对于每个新数字:
    1. 如果栈顶元素等于当前数字,就合并(弹出栈顶,将当前数字+1作为新的数字,继续与栈顶比较,直到不能合并为止)。
    2. 否则,直接入栈。
  • 最终栈中会留下一些数,我们取栈中的最大值作为答案。

代码实现:

C++
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
int main() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    stack<int> st;
    for (int i = 0; i < n; i++) {
        int x = a[i];
        // 不断与栈顶合并
        while (!st.empty() && st.top() == x) {
            st.pop();
            x++;
        }
        st.push(x);
    }
    int ans = 0;
    while (!st.empty()) {
        ans = max(ans, st.top());
        st.pop();
    }
    cout << ans << endl;
    return 0;
}
原文