HDU 3347:Calculate the expression

Calculate the expression

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 399    Accepted Submission(s): 214


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<map>
#include<string>
using namespace std;

const int MAX=1000000;
string str,var;
int n;

int Str2Int(string s)
{
	int end=0,a=1;
	if(s[0]=='-')
		end=1;
	int res=0;
	for(int i=s.size()-1;i>=end; i--)
	{
		res += (s[i]-'0')*a;
		a *= 10;
	}
	if(end) return -res;
	return res;
}

int main()
{
	map<string,int> m;
	int T,i,value;
	char c;
	cin>>T;
	while(T--)
	{
		cin>>n;
		for(i=0;i<n-1;i++)
		{
			cin>>var>>c>>value;
			m[var]=value;
		}
		int tmp,ans=0;
		bool plus=true; //+ or -
		while(cin>>str)
		{
			if(str=="?") break;
			else if(str=="+") plus=true;
			else if(str=="-") plus=false;
			else if(str=="=") continue;
			else if(str[0]>='a' && str[0]<='z')
			{
				if(plus) ans += m[str];
				else ans -= m[str];
			}
			else
			{
				tmp=Str2Int(str);
				if(plus) ans += tmp;
				else ans -= tmp;
			}
		}
		cout<<ans<<endl;
	}
	system("pause");
	return 0;
}


你可能感兴趣的:(String,Integer,System,input,each,output)