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;
}

 

posted @ 2016-07-02 22:33  Fighting_Heart  阅读(138)  评论(0编辑  收藏  举报