HDU3347Calculate the expression 【map】

来源:互联网 发布:融资租赁软件市场 编辑:程序博客网 时间:2024/06/03 19:57


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
34aa = 1bb = -1aa = 2aa + bb + 11 = ?11 + 1 = ?11 + -1 = ?
 

Sample Output
1220


#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
原创粉丝点击