【题解搬运】PAT_L1-009 N个数求和

从我原来的博客上搬运。原先blog作废。
(伪)水题+1,旨在继续摸清这个blog(囧

题目

就是求N个数字的和。麻烦的是,这些数字是以有理数“分子/分母”的形式给出的,你输出的和也必须是有理数的形式。

题解

对读入,可以使用scanf(“%d/%d”,…);来解决读入问题(scanf很强的!
然后以为自己稳了。。。结果TLE了
问题在哪里呢?在gcd那里,我一开始加上了b与a的大小判断,然而其实不应该这么做!这样做破坏了尾递归(让gcc没法优gao化shi了),极大的减慢了gcd的速度。

后来删掉了if,引出了个WA2333
问题在于负数分数的问题,处理如下,在两个地方加以处理了。
水题想搞事也很容易啊,大意要不得。

代码

#include <bits/stdc++.h>
using namespace std;

#define f1(x,y) for(int x=1;x<=y;++x)
#define f0(x,y) for(int x=0;x!=y;++x)
#define bf1(x,y,z) for(int x=y;x>=z;--x)
#define bf0(x,y,z) for(int x=y;x!=z;--x)
typedef long long ll;
typedef unsigned long long ull;

int gcd(int a,int b)
{
//    if(b>a) swap(a,b);
    return (b==0)?a:(gcd(b,a%b));
}
int lcm(int a,int b)
{
    return a/gcd(a,b)*b;
}
int main()
{
    int n;
    scanf("%d",&n);
    int tota,totb;
    f1(i,n)
    {
        int a,b;
        scanf("%d/%d",&a,&b);
        if(i==1)
        {
            tota=a;totb=b;
        }
        else
        {
            int tmpb=b;
            tmpb=lcm(b,totb);
            tota=tota*tmpb/totb+a*tmpb/b;
            totb=tmpb;
        }
        int g=gcd(abs(tota),abs(totb));
        tota/=g;totb/=g;
        //cout<<tota<<" "<<totb<<endl;
    }
    if(abs(tota)>=abs(totb) || tota==0)
    {
        printf("%d",tota/totb);
        if(tota%totb==0)
            printf("\n");
        else
            printf(" %d/%d\n",abs(tota)%abs(totb),totb);
    }
    else printf("%d/%d\n",tota,totb);
    //printf("%d/%d\n",tota,totb);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值