很容易想到用堆处理,但会有操作使得数值远大于long long.此时灵活将范围缩小,细节见代码。
#include<iostream>
#include<stack>
using namespace std;
typedef long long ll;
const ll Max = pow(2, 32) - 1;
stack<ll> sta;
int main()
{
ll a = 0;
int t;cin >> t;
ll sum = 1;
ll ans = 0;
int f = 0;
sta.push(1);
while (t--)
{
string str;cin >> str;
ll num;
if (str == "for")
{
cin >> num;
sum *= num;
if (sum > Max)sum = Max + 1;
sta.push(sum);
}
if (str == "end")
{
sta.pop();
sum = sta.top();
}
if (str == "add")
{
if (ans+sum > Max) f = 1;
ans += sum;
}
}
if (f)cout << "OVERFLOW!!!" << endl;
else cout << ans << endl;
}