nyoj 1272 表达式求值
来源:互联网 发布:子曰好学近乎知原文 编辑:程序博客网 时间:2024/05/18 04:29
- 输入
- 【标准输入】 第一行: T 表示要计算的表达式个数 (1≤ T ≤ 10) 接下来有 T 行, 每行是一个字符串,表示待求的表达式,长度<=1000
- 输出
- 【标准输出】 对于每个表达式,输出一行,表示对应表达式的值。
- 样例输入
312+2*312*(2+3)12*(2+3)+Smax(333,220+280)
- 样例输出
1860
69
#include <stdio.h>
#include <string.h>
#include <stack>
#define max(a, b) a > b ? a : b
using namespace std;
int main()
{
char s[1010];
stack<int > std;
stack<char > stc;
int T, i, j;
scanf("%d", &T);
while(T --)
{
int count = 0;
scanf("%s", &s[1]);
s[0] = '(';
int len = strlen(s);
s[len] = ')';
for(i = 0;i <= len;i ++)
{
if(s[i] == '(')
{
stc.push(s[i]);
}
else if(s[i] == 'S')
{
stc.push('(');
i = i + 3;
}
else if(s[i] >= '0' && s[i] <= '9')
{
int t = 0;
while(s[i] >= '0' && s[i] <= '9')
{
t = t * 10 + s[i++] - '0';
}
i --;
std.push(t);
}
else if(s[i] == '+')
{
char c = stc.top();//printf("+%c%d\n", c, ++count);
if(c == '+' || c == '*')
{
int a = std.top();std.pop();
int b = std.top();std.pop();
int x;
switch(c)
{
case '+': x = a + b;break;
case '*': x = a * b;break;
}
std.push(x);
stc.pop();
}
stc.push(s[i]);
}
else if(s[i] == '*')
{
char c = stc.top();//printf("*%c%d\n", c, ++count);
if(c == '*')
{
int a = std.top();std.pop();
int b = std.top();std.pop();
int x = a * b;
std.push(x);
stc.pop();
}
stc.push(s[i]);
}
else if(s[i] == ')')
{
char c = stc.top();//printf(")%c%d\n", c, ++count);
while(c == '+' || c == '*')
{
int a = std.top();std.pop();
int b = std.top();std.pop();
int x;
switch(c)
{
case '+': x = a + b;break;
case '*': x = a * b;break;
}
std.push(x);
stc.pop();
c = stc.top();
//printf(")x=%d\n", x);
}
if(stc.top() == '(')
{//printf("(%d\n", ++count);
stc.pop();
if(!stc.empty())
{
char c = stc.top();
if(c == ',')
{
stc.pop();
if(stc.top()=='(')
{
int a = std.top();std.pop();
int b = std.top();std.pop();
// printf("a=%d b=%d\n", a, b);
int x = 0, y = 0;
while(a)
{
x = x + a%10;
a /= 10;
}
while(b)
{
y = y + b%10;
b /= 10;
}
y = max(x, y);
std.push(y);
stc.pop();
}
}
}
}
}
else if(s[i] == ',')
{
char c = stc.top();//printf(")%c%d\n", c, ++count);
while(c == '+' || c == '*')
{
int a = std.top();std.pop();
int b = std.top();std.pop();
int x;
switch(c)
{
case '+': x = a + b;break;
case '*': x = a * b;break;
}
std.push(x);
stc.pop();
c = stc.top();
}
if(stc.top() == '(')stc.pop();
stc.push(',');
stc.push('(');
}
}
printf("%d\n", std.top());
std.pop();
}
return 0;
}
- nyoj 1272 表达式求值
- NYOJ-1272 表达式求值
- nyoj 1272 表达式求值
- nyoj 1272(表达式求值)
- NYOJ 1272 表达式求值 (字符串处理)
- NYOJ 35 表达式求值
- NYOJ 35表达式求值
- NYOJ 409表达式求值
- NYOJ-35-表达式求值
- nyoj 35 表达式求值
- NYOJ 35 表达式求值
- 表达式求值 nyoj
- NYOJ 35 表达式求值
- NYOJ 35-表达式求值
- nyoj 305 表达式求值
- NYOJ,305,表达式求值
- nyoj-305-表达式求值
- nyoj 35 表达式求值
- 入门级Hadoop集群搭建详细教程(六):yum本地仓库与远程仓库配置
- generalized Linear Models
- AIX执行xost +但图形检测仍不通过
- 经典算法题每日演练——第一题 百钱买百鸡
- C++获取运行exe路径和名称
- nyoj 1272 表达式求值
- 经典算法题每日演练——第二题 五家共井
- 浅谈CSRF攻击方式
- 【PMP】PMBOK 笔记 第5章 项目范围管理
- Mac下Eclipse读取不到环境变量
- 经典算法题每日演练——第三题 猴子吃桃
- android AsyncTask实现多线程断点续传
- vue 初使用
- 天籁数学——数列篇(1)