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

Posted Fighting Heart

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT (Advanced Level) 1081. Rational Sum (20)相关的知识,希望对你有一定的参考价值。

简单模拟题。

#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==0) return a;
    return gcd(b,a%b);
}

FenShu ADD(FenShu a,FenShu b)
{
    FenShu res(0,1);
    res.fz=a.fz*b.fm+b.fz*a.fm;
    res.fm=a.fm*b.fm;

    if(res.fz!=0)
    {
        long long GCD=gcd(abs(res.fz),abs(res.fm));
        res.fz=res.fz/GCD;
        res.fm=res.fm/GCD;
    }
    else
    {
        res.fz=0;
        res.fm=1;
    }
    return res;
}

int main()
{
    int n; scanf("%d",&n);
    FenShu ans(0,1);
    for(int i=1;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==0) printf("0\n");
    else
    {
        if(ans.fz%ans.fm==0) 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 0;
}

 

以上是关于PAT (Advanced Level) 1081. Rational Sum (20)的主要内容,如果未能解决你的问题,请参考以下文章

PAT (Advanced Level) 1025. PAT Ranking (25)

PAT Advanced Level 1044

PAT Advanced Level 1043

PAT Advanced Level 1079

PAT Advanced Level 1095

PAT Advanced Level 1038