HDOJ3347Calculate the expression(字符串处理)

Xredman posted @ Mar 19, 2010 06:30:23 AM in Algorithm with tags HDU 字符串处理 , 1125 阅读

        此题是对一些表达式进行求解,题目可能告诉一些变量的值,要求解出由这些变量组成的一个表达式的值

 

//2211264	2010-03-19 17:05:35	Wrong Answer	3347	15MS	304K	1111 B	C++
//2211343	2010-03-19 17:17:21	Accepted	3347	15MS	304K	1232 B	C++
#include <iostream>
#include <string>
#include <map>
#include <cctype>
using namespace std;

map<string, int> M; 

int main()
{
	int T, n;
	string ss, ts;
	int res;
	int flag;
	cin>>T;
	while(T--)
	{
		cin>>n;
		M.clear();
		while(n--)
		{
			
			res = 0; flag = 1;
			while(cin>>ss && ss != "=")
			{
				ts = ss;
				if(isalpha(ss[0]))
				{//是表达式
					res += M[ss] * flag; 
				}
				else if(ss == "+")
				{
					flag = 1;	
				}else if(ss == "-")
				{
					flag = -1;
				}else
				{
					ts = ss;
					if(ss[0] == '-')
					{
						ts = ss.substr(1, ss.length());
						if(flag == 1)
							res -= atoi(ts.c_str());
						else
							res += atoi(ts.c_str());
					}
					else
					{
						if(flag == 1)
							res += atoi(ts.c_str());
						else
							res -= atoi(ts.c_str());
					}
					
				}
			}
			cin>>ss;
			if(ss == "?")
				cout<<res<<endl;
			else
			{
				M[ts] = atoi(ss.c_str());
			}
		}
	}
	return 0;
}
/*
5

3
a = -1
b = -1
a + b - 2 = ?
0

100
1
-111 + -9 = ?
-10



*/

 

 






NCERT Term 1 Sample 说:
Sep 25, 2022 06:29:08 AM

Candidates who to know the examination pattern or question paper style and want topic wise important questions for all subjects, NCERT Term 1 Sample Paper Class 10 with those candidates in mind here we supplied the NCERT Term-1 Sample Paper 2023 Class 10 for Session exams of SA, FA and Assignments of all subjects and languages as per the newly revised syllabus & curriculum.Candidates who to know the examination pattern or question paper style and want topic wise important questions for all subjects.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter