• 【题解搬运】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("
    ");
            else
                printf(" %d/%d
    ",abs(tota)%abs(totb),totb);
        }
        else printf("%d/%d
    ",tota,totb);
        //printf("%d/%d
    ",tota,totb);
        return 0;
    }
    如非注明,原创内容遵循GFDLv1.3发布;其中的代码遵循GPLv3发布。
  • 相关阅读:
    Spring 整合Hibernate与Struts2
    Spring @注解详解(转)
    Spring 事务
    Spring c3p0支持Hibernate配置
    Spring c3p0连接池配置
    Spring dbcp连接池配置与示例(以及JDBCTemplate的使用)
    struts转换器详解
    struts拦截器详解
    struts拦截器的使用
    OGNL表达式详解
  • 原文地址:https://www.cnblogs.com/samhx/p/9652096.html
Copyright © 2020-2023  润新知