题意
计算只包含加减和括号的分式计算式
题解
一开始尝试去括号,但是没有办法很好解决重叠括号的问题,指的是
(
(
(
)
)
)
((()))
((()))。
这个时候我不好判断。
如果我们记录两个标记,
f
f
f表示当前加减号,
f
f
ff
ff表示当前括号产生的变号影响。
以
/
/
/来标识和记录一个分式。
直接计算即可,每次遇到一个左括号,
f
f
f应该变为
1
1
1,因为此时相当于一个加号。
(
+
a
)
(+a)
(+a)
变号的影响乘以当前加减号的影响为
f
∗
f
f
f*ff
f∗ff
即可。
#include<bits/stdc++.h>
#define FOR(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
const int maxn = 200050;
typedef long long ll;
string str;
stack<int>s;
ll f,ff;
struct node{
ll up,down;
}tp,ans;
void cal(int now){
int l=now-1;
for(;l>=0;l--){
if(str[l]<'0'||str[l]>'9')break;
}
tp.up=0;
for(int i=l+1;i<now;i++){
tp.up=tp.up*10+str[i]-'0';
}
tp.down=0;
for(int i=now+1;i<str.size()&&str[i]>='0'&&str[i]<='9';i++){
tp.down=tp.down*10+str[i]-'0';
}
}
void deal(){
ll u=ans.up,d=ans.down;
ans.up=u*tp.down+f*ff*tp.up*d;
ans.down=d*tp.down;
ll g=__gcd(abs(ans.up),abs(ans.down));
if(g==0)while(1);
ans.up/=g,ans.down/=g;
}
int main(){
while(cin>>str){
f=ff=1;
ans.up=0,ans.down=1;
for(int i=0;i<str.size();i++){
if(str[i]=='+')f=1;
else if(str[i]=='-')f=-1;
else if(str[i]=='('){
f=1;
if(i){
if(str[i-1]=='-')ff*=-1,s.push(-1);
else ff*=1,s.push(1);
}
else s.push(1);
}
else if(str[i]==')'){
ff*=s.top();
s.pop();
}
else if(str[i]=='/'){
cal(i);
deal();
}
}
cout<<ans.up<<"/"<<ans.down<<endl;
}
}