#define LOCAL
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
using namespace std;
typedef long long ll;
ll gcd(ll a,ll b){
return b==0?a:gcd(b,a%b);
}
struct Fraction{
ll up,down;
};
Fraction reduction(Fraction a){
if(a.down<0){
a.up=-a.up;
a.down=-a.down;
}
if(a.up==0){
a.down=1;
}else{
int d=gcd(abs(a.up),abs(a.down));
a.down/=d;a.up/=d;
}
return a;
}
Fraction add(Fraction a,Fraction b){
Fraction res;
res.up=a.up*b.down+a.down*b.up;
res.down=a.down*b.down;
return reduction(res);
}
void showResult(Fraction r){
reduction(r);
if(r.down==1) printf("%lld\n",r.up);
else if(abs(r.up)>r.down) printf("%lld %lld/%lld\n",r.up/r.down,abs(r.up)%r.down,r.down);
else printf("%lld/%lld\n",r.up,r.down);
}
int main()
{
#ifdef LOCAL
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
#endif // LOCAL
int n;
cin>>n;
Fraction sum,t;
sum.up=0;sum.down=1;
for(int i=0;i<n;i++){
scanf("%lld/%lld",&t.up,&t.down);
sum=add(sum,t);
}
showResult(sum);
return 0;
}
关键:注意细节,比如负数,分子为零,分子等于分母,还有为了防止溢出用long long
【PAT】1081. Rational Sum
最新推荐文章于 2021-03-02 14:14:56 发布