HDU3347Calculate the expression 【map】

16 篇文章 0 订阅
5 篇文章 0 订阅


http://acm.hdu.edu.cn/showproblem.php?pid=3347


Problem Description
You may find it’s easy to calculate the expression such as:
a = 3
b = 4
c = 5
a + b + c = ?
Isn’t it?
 

Input
The first line contains an integer stands for the number of test cases.
Each test case start with an integer n stands for n expressions will follow for this case.
Then n – 1 expressions in the format: [variable name][space][=][space][integer] will follow.
You may suppose the variable name will only contain lowercase letters and the length will not exceed 20, and the integer will between -65536 and 65536.
The last line will contain the expression you need to work out.
In the format: [variable name| integer][space][+|-][space][variable name| integer] …= ?
You may suppose the variable name must have been defined in the n – 1 expression and the integer is also between -65536 and 65536. 
You can get more information from the sample.
 

Output
For each case, output the result of the last expression.
 

Sample Input
  
  
3 4 aa = 1 bb = -1 aa = 2 aa + bb + 11 = ? 1 1 + 1 = ? 1 1 + -1 = ?
 

Sample Output
  
  
12 2 0


#include<iostream>
#include<cstdio>
#include<map>
using namespace std;
string name,name2;
map<string,int> cal;

int zhengxing(string str)
{
    int fflag=0;
    int shi=1,anss=0;
    if(str[0]=='-')
        fflag=1;
    for(int i=str.size()-1;i>=fflag;i--)
    {
        anss+=(str[i]-'0')*shi;
        shi=shi*10;
    }
    if(fflag)
        return -anss;
    else
        return anss;

}
int main()
{
    int T,n,integer;
    char c;
    cin>>T;
    while(T--)
    {
        cin>>n;
        for(int i=0;i<n-1;i++)
        {
            cin>>name>>c>>integer;
            cal[name]=integer;
        }

        int flag=1,ans=0;
        while(cin>>name2)
        {
            if(name2[0]>='a'&&name2[0]<='z')
            {
                if(flag)
                {
                    ans+=cal[name2];
                }
                else
                {
                    ans-=cal[name2];
                }
            }
            else if(name2=="?") break;
            else if(name2=="=") continue;
            else if(name2=="+")
                flag=1;
            else if(name2=="-")
                flag=0;
            else
            {
                if(flag)
                    ans+=zhengxing(name2);
                else
                    ans-=zhengxing(name2);
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值