记录编号 |
121599 |
评测结果 |
AAAAAAAAAA |
题目名称 |
有括号的算术表达式运算 |
最终得分 |
100 |
用户昵称 |
HouJikan |
是否通过 |
通过 |
代码语言 |
C++ |
运行时间 |
0.004 s |
提交时间 |
2014-09-20 17:02:23 |
内存使用 |
0.31 MiB |
显示代码纯文本
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <list>
#include <vector>
#include <ctime>
#include <iterator>
#include <functional>
#define pritnf printf
#define scafn scanf
#define For(i,j,k) for(int i=(j);i<=(k);(i)++)
using namespace std;
typedef long long LL;
typedef unsigned int Uint;
const int INF=1000000;
//==============struct declaration==============
struct Items
{
int p1,p2;
Items (int p1=0,int p2=0):p1(p1),p2(p2){}
bool operator <(const Items &rhs) const
{
return p2-p1<rhs.p2-rhs.p1;
}
};
//==============var declaration=================
const int MAXN=1010;
string Exp;
//==============function declaration============
void solve();
int caculate(int a,int b,char ch);
int pow(int a,int b);
//==============main code=======================
int main()
{
string FileName="ssexpress";//程序名
string FloderName="COGS";//文件夹名
freopen((FileName+".in").c_str(),"r",stdin);
freopen((FileName+".out").c_str(),"w",stdout);
#ifdef DEBUG
system(("cp C:\\Users\\Administrator\\Desktop\\"+FloderName+"\\standard.cpp C:\\Users\\Administrator\\Desktop\\"+FloderName+"\\submit.txt").c_str());
clock_t Start_Time=clock();
#endif
getline(cin,Exp,'@');
Exp='('+Exp+')';
solve();
#ifdef DEBUG
clock_t End_Time=clock();
printf("\n\nTime Used: %.4lf Ms\n",double(End_Time-Start_Time)/CLOCKS_PER_SEC);
#endif
return 0;
}
//================fuction code====================
void solve()
{
stack <char> S;
stack <int> N;
int len=Exp.length()-1;
For(i,0,len)
{
if (Exp[i]>='0'&&Exp[i]<='9')
N.push(Exp[i]-'0');
else
{
if (Exp[i]=='(')
S.push('(');
else if (Exp[i]=='^')
S.push('^');
else if (Exp[i]=='/'||Exp[i]=='*')
{
char ch;
while (!S.empty()&&(S.top()=='/'||S.top()=='*'||S.top()=='^'))
{
ch=S.top();S.pop();
int b=N.top();N.pop();
int a=N.top();N.pop();
N.push(caculate(a,b,ch));
}
S.push(Exp[i]);
}
else if (Exp[i]=='+'||Exp[i]=='-')
{
char ch;
while (!S.empty()&&(S.top()!='('))
{
ch=S.top();S.pop();
int b=N.top();N.pop();
int a=N.top();N.pop();
N.push(caculate(a,b,ch));
}
S.push(Exp[i]);
}
else if (Exp[i]==')')
{
char ch;
while (S.top()!='(')
{
ch=S.top();S.pop();
int b=N.top();N.pop();
int a=N.top();N.pop();
N.push(caculate(a,b,ch));
}
S.pop();
}
}
}
printf("%d\n",N.top());
}
int caculate(int a,int b,char ch)
{
if (ch=='+')
return a+b;
if (ch=='*')
return a*b;
if (ch=='-')
return a-b;
if (ch=='/')
return a/b;
if (ch=='^')
return pow(a,b);
}
int pow(int a,int b)
{
int res=1;
For(i,1,b)
res*=a;
return res;
}