前置知识
- 最大公因数函数。
- 分数的加减乘除。
- 括号串匹配。
思路:递归
首先先预处理出每个左括号匹配的右括号,设每个左括号对应的右括号的位置是 。
我们为算出括号内的 ,维护一个指针 ,每次如果 是左括号,就跳到 的位置,并计算里面的数,否则把数字改写成分数的形式,并往前跳一步。共计跳三次
最后根据定义 计算括号内的分数数值。
另外,如果跳三次后没有跳在 上,说明一个括号内元素个数不为 3,返回特定值,代表出错。
一些细节
- 建议把分数封装起来并重载运算符,使代码更美观。
- 注意递归时 中是否包括最外层的括号,要统一。如果包括,最后一次应跳在 上。
- 输入不合法的两种形式:
- 括号串无法匹配。
- 一个括号内元素个数不为 3。
- 注意时间复杂度,本代码是 的。
代码
#include<iostream>
#include<stack>
#define ll long long
using namespace std;
const int N=128;
int n;
string s;
stack<int> S;
int to[N];
bool F=1;
ll gcd(ll u,ll v){//求最大公因数
if(!v) return u;
if(u<v) swap(u,v);
return gcd(v,u%v);
}
//封装分数
struct Num{
ll a,b;
//重载+运算符
Num operator+(const Num &other) const{
Num res;
ll g=gcd(b,other.b);
res=(Num){(a*other.b+b*other.a)/g,b*other.b/g};
return res;
}
//重载/运算符
Num operator/(const Num &other) const{
Num res;
res=(Num){a*other.b,b*other.a};
ll g=gcd(a*other.b,b*other.a);
res.a/=g;res.b/=g;
return res;
}
bool operator==(const Num &other) const{
return a==other.a&&b==other.b;
}
};
Num no=(Num){-1,0},ans;
Num calc(int l,int r){//统一成不包括最外层的括号
Num a,b,c,res;int p=l;
if(s[p]=='('){a=calc(p+1,to[p]-1);p=to[p]+1;}else a=(Num){s[p]-'0',1},p++;
//如果第一个元素不是整数而是繁分数,就调用calc,否则将其改写成分数的形式
if(s[p]=='('){b=calc(p+1,to[p]-1);p=to[p]+1;}else b=(Num){s[p]-'0',1},p++;
if(s[p]=='('){c=calc(p+1,to[p]-1);p=to[p]+1;}else c=(Num){s[p]-'0',1},p++;
if(p!=r+1) return no;
if(a==no||b==no||c==no) return no;
//当返回no时,说明存在一个括号内元素个数不为3的情况
res=a+b/c;
return res;
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
char c;cin>>c;
s+=c;
}
//括号串匹配
for(int i=0;i<n;i++){
if(s[i]=='(') S.push(i);
else if(s[i]==')'){
if(S.empty()){
F=0;
break;
}
int j=S.top();S.pop();
to[j]=i;
}
}
if(!S.empty()) F=0;
if(!F){
//当F=0时,说明括号串不合法,输出-1
printf("-1");
return 0;
}
//计算答案
ans=calc(1,n-2);
//由于最外层的括号要被忽略,所以应为1,n-2
if(ans==no) printf("-1");
else printf("%lld %lld\n",ans.a,ans.b);
}