CF-1175 B.Catch Overflow!

题目大意:有一个初始变量,值为0,三种操作 

for x 一个循环的开始,循环x次

end 一个循环的结束

add 将变量值加一

问最后变量的值是否超过2^32-1,若超过,输出一串字符,不超过则输出变量的值

做法:对于循环结构,有两种思路,一种是先算出内循环的值,然后再一层一层的向外算;还有一种是从外向内进行变量操作。我们平时的思考方法应该与思路一比较相似,但是在这个题中会发现很难实现,比如说一个循环内嵌套了两个并列的循环结构,这就让人很头大。所以本题应该采用思路二,思路二一旦想明白了,代码就不难写了。

#include<iostream>
#include<cstdio>
#define maxn 100010
#define Mod 4294967295LL
using namespace std;
long long st[maxn],ans;
int n,top;
char s[100];
int main(){
    scanf("%d",&n);
    st[0]=1;
    while(n--){
        scanf("%s",s+1);
        if(s[1]=='a'){
            ans+=st[top];
            if(ans>Mod){
                puts("OVERFLOW!!!");
                return 0;
            }
        }
        else if(s[1]=='f'){
            long long x;
            cin>>x;
            top=top+1;
            st[top]=st[top-1]*x;
            if(st[top]>Mod)st[top]=Mod+1;
        }
        else top--;
    }
    if(ans>Mod)puts("OVERFLOW!!!");
    else cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/thmyl/p/11704680.html