比賽

 
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stack>
#include<string.h>
#include<map>
using namespace std;
map<char,long long >M;
map<char,int>ma;
string tem;
char root[2000];
int Judge(char a)
{
    if(a>='A')
        return 1;
    return 0;
}
void Convect(char ch[])
{
    stack<char> start;
    int len=strlen(ch);
    int i;
    int Top=0;
    for(i=0; i<len; i++)
    {
        if(Judge(ch[i]))
        {
            root[Top++]=ch[i];
        }
        else
        {
            switch(ch[i])
            {
            case '+':
            case '-':
            case '/':
            case '*':
                while((!start.empty())&&ma[start.top()]>=ma[ch[i]])
                {
                    root[Top++]=start.top();
                    start.pop();
                }
                start.push(ch[i]);
                break;
            }
        }
    }
    while(!start.empty())
    {
        root[Top++]=start.top();
        start.pop();
    }
    root[Top]=0;
}
long long sum()
{
    stack<long long> end;
    int len=strlen(root);
    int i;
    for(i=0; i<len; i++)
    {
        if(Judge(root[i]))
        {
            end.push(M[root[i]]);
        }
        else
        {
            long long num1,num2;
            num1=end.top();
            end.pop();
            num2=end.top();
            end.pop();
            switch(root[i])
            {
            case '/':
                 end.push(num2/num1);
                 break;
            case '*':
                end.push(num1*num2);
                break;
            case '+':
                end.push(num1+num2);
                break;
            case '-':
                end.push(-num1+num2);
                break;
            }
        }
    }
    return end.top();
}
int main()
{
    long long ans;
    char a[2000];
    ma['*']=2;
    ma['/']=2;
    ma['+']=1;
    ma['-']=1;
    while(cin>>tem)
    {
        M.clear();
        int flag=0;
        memset(root,0,sizeof(root));
        for(int i=0; i<tem.size()-1; i++)
        {
            if(tem[i]=='/'&&tem[i+1]=='0')
            {
                printf("impossible\n");
                flag=1;
                break;
            }
        }
        if(flag)
         continue;
        int Len=0;
        char step='A';
        ans=0;
        for(int i=0; i<tem.size(); i++)
        {
            if(tem[i]<'0'||tem[i]>'9')
            {
                M[step]=ans/10;
                a[Len++]=step;
                step++;
                a[Len++]=tem[i];
                ans=0;
                continue;
            }
            ans=(ans+tem[i]-'0')*10;
        }
        M[step]=ans/10;
        a[Len++]=step;
        step++;
        a[Len++]='\0';
        Convect(a);
        ans=sum();
        printf("%lld\n",ans);
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章