#include <iostream>
#include <string>
using namespace std;
void getSubExpr( const string& expr, int idx, string& res);
int main()
{
char name;
string expr;
string query;
string e, res;
int num[100];
char tmp;
int n;
int x = 0;
while (true)
{
cin>>name;
if (name == '*') break;
if (x) cout<<endl;
x = 1;
cout<<"Expression "<<name<<":"<<endl;
getchar(); getchar();
cin>>expr;
cin>>n;
for (int i = 0; i < n; i++)
{
int t=0;
while(cin>>num[t])
{
cin.get(tmp);
t++;
if (tmp == '/n') break;
}
for (int j = 0; j < t; j++)
{
cout<<"op("<<num[t-1-j]<<",";
}
cout<<name;
for (int j = 0; j < t; j++)
{
cout<<")";
}
cout<<"=";
e = expr;
for (int j=0; j<t; j++)
{
getSubExpr(e, num[j], res);
e = res;
}
cout<<res<<endl;
}
}
}
//使用指定的操作符, 看是否能分开表达式
inline bool process(const string& expr, int idx, string& res, char op)
{
int n = expr.length();
int parenthese = 0;
int st = 0;
int iCnt = 0;
for (int pos = 0; pos < n; pos++)
{
if ( parenthese==0 && expr[pos] == op )
{
iCnt++;
if (iCnt == idx)
{
res = expr.substr(st, pos-st);
return true;
}
st = pos+1;
} else if ( expr[pos] == '(' ) parenthese++;
else if(expr[pos] == ')') parenthese--;
}
if (iCnt)
{
res = expr.substr(st); return true;
}
return false;
}
void getSubExpr( const string& expr, int idx, string& res)
{
int n = expr.length();
if (process(expr, idx, res, '+')) return;
if (process(expr, idx, res, '*')) return;
if (process(expr, idx, res, '^')) return;
//注意一定要最后判断括号, 它优先级最高
if (expr[0] == '(' && expr[n-1]==')')
{
res = expr.substr(1, n-2);
return;
}
res = expr;
}
zoj1014 不使用表达式树 ac
最新推荐文章于 2019-07-17 11:13:00 发布