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

来源:互联网 发布:mysql engine=myisam 编辑:程序博客网 时间:2024/06/05 08:14

从我原来的博客上搬运。原先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;}
原创粉丝点击