PAT (Advanced Level) 1081. Rational Sum (20)

时间:2021-05-13 17:46:42

简单模拟题。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std; struct FenShu
{
long long fz,fm;
FenShu(long long a,long long b)
{
fz=a;
fm=b;
}
}; long long gcd(long long a,long long b)
{
if(b==) return a;
return gcd(b,a%b);
} FenShu ADD(FenShu a,FenShu b)
{
FenShu res(,);
res.fz=a.fz*b.fm+b.fz*a.fm;
res.fm=a.fm*b.fm; if(res.fz!=)
{
long long GCD=gcd(abs(res.fz),abs(res.fm));
res.fz=res.fz/GCD;
res.fm=res.fm/GCD;
}
else
{
res.fz=;
res.fm=;
}
return res;
} int main()
{
int n; scanf("%d",&n);
FenShu ans(,);
for(int i=;i<=n;i++)
{
long long fz,fm; scanf("%lld/%lld",&fz,&fm);
FenShu t(fz,fm);
ans=ADD(ans,t);
}
//printf("%d/%d\n",ans.fz,ans.fm);
if(ans.fz==) printf("0\n");
else
{
if(ans.fz%ans.fm==) printf("%lld\n",ans.fz/ans.fm);
else if(abs(ans.fz)<ans.fm) printf("%lld/%lld\n",ans.fz,ans.fm);
else
{
long long d=ans.fz/ans.fm;
ans.fz=ans.fz-d*ans.fm;
printf("%lld %lld/%lld\n",d,ans.fz,ans.fm);
}
}
return ;
}