Calculate the expression

    xiaoxiao2021-03-25  56

    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; }
    转载请注明原文地址: https://ju.6miu.com/read-35342.html

    最新回复(0)