【1081 20 分数运算】 Rational Sum

传送门

题意

给定\(n\)个分数形式为a/b,求它们相加的结果如果分子大于分母先输出约分后的整数后分数,如果正好只输出整数,为\(0\)的时候只输出\(0\)

数据范围

\(n\leq 100\)

题解

  • 每次暴力通分绝对值后约去gcd
  • 最后根据结果分类输出

Code

#include<bits/stdc++.h>
using namespace std;
#define fi first 
#define se second
#define ll long long
typedef pair<ll,ll> pii;
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
int main(){
	int n; cin>>n;
	pii now={0,1};
	for(int i=0;i<n;i++) {
		pii t; scanf("%lld/%lld",&t.fi,&t.se);
		now.fi*=abs(t.se); t.fi*=abs(now.se);
		now.se*=abs(t.se);
		now.fi+=t.fi;
		if(now.fi==0 && i!=0 && i!=n-1) {now.se=1; continue;}
		ll d=gcd(now.fi,now.se);
		now.fi/=d; now.se/=d;
	}
	if(now.fi>now.se){
		ll t=now.fi/now.se;
		now.fi%=now.se;
		cout<<t;
		if(now.fi!=0) printf(" %lld/%lld",now.fi,now.se);
	} 
	else if(now.fi!=0) printf("%lld/%lld",now.fi,now.se);
	else printf("0");
}
posted @ 2021-03-05 23:27  Hyx'  阅读(61)  评论(0)    收藏  举报