跳到正文

题解

题解:P14088 [ICPC 2023 Seoul R] Fraction

inmoob约 4 分钟
原文

这是 2025年10月1日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年10月1日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 4 分钟
题目
P14088

版本

  1. v2当前
  2. v1

前置知识

  • 最大公因数(gcd)函数
  • 分数的加减乘除
  • 括号串匹配

思路:递归

首先先预处理出每个左括号匹配的右括号,再递归即可。

一些细节

  • 建议把分数封装起来并重载运算符,使代码更美观。
  • 注意递归时[l,r]中是否包括最外层的括号,要统一。
  • 个人感觉不开long long见祖宗。
  • 输入不合法的两种形式:
    • 括号串无法匹配。
    • 一个括号内元素个数不为3。
  • 注意时间复杂度。

代码

C++
#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);//由于最外层的括号 
	if(ans==no) printf("-1");
	else printf("%lld %lld\n",ans.a,ans.b);
}