问题理解
- 有一个正整数序列,每次可以合并相邻且相等的两个数,合并后变成一个比原来大 1 的数。 重复这个过程,直到无法合并为止。 不同的合并顺序可能导致最终的最大数不同,我们要找出可能得到的最大数。
关键思路
这个问题其实是一个经典的“合并相邻相同数”问题,可以用贪心 + 栈的方法解决。
核心思想:
- 从左到右扫描数列,用一个栈来保存当前无法合并的数。
- 对于每个新数字:
- 如果栈顶元素等于当前数字,就合并(弹出栈顶,将
当前数字+1作为新的数字,继续与栈顶比较,直到不能合并为止)。 - 否则,直接入栈。
- 如果栈顶元素等于当前数字,就合并(弹出栈顶,将
- 最终栈中会留下一些数,我们取栈中的最大值作为答案。
代码实现:
#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;
}