码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-07-02 22:55:48      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

简单模拟题。

#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)

标签:

原文地址:http://www.cnblogs.com/zufezzt/p/5636195.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!