A1081 Rational Sum (20)

时间限制 1000 ms 内存限制 65536 KB 代码长度限制 100 KB 判断程序 Standard (来自 小小)

题目描述
Given N rational numbers in the form “numerator/denominator”, you are supposed to calculate their sum.

输入描述:
Each input file contains one test case. Each case starts with a positive integer N (<=100), followed in the next line N rational numbers “a1/b1 a2/b2 …” where all the numerators and denominators are in the range of “long int”. If there is a negative number, then the sign must appear in front of the numerator.

输出描述:
For each test case, output the sum in the simplest form “integer numerator/denominator” where “integer” is the integer part of the sum, “numerator” < “denominator”, and the numerator and the denominator have no common factor. You must output only the fractional part if the integer part is 0.

输入例子:
5
2/5 4/15 1/30 -2/60 8/3

输出例子:
3 1/3

题解:
此题目涉及到分数的加减运算,先按照普通的步骤进行加减运算,然后进行约分运算,最后按照需求判断是否是假分数,这这里可以先不考虑数字的正负。

#include <bits/stdc++.h>
#include <stdlib.h>
using namespace std;
#define vi vector<int>
#define pii pair<int,int>
#define x first
#define y second
#define all(x) x.begin(),x.end()
#define pb push_back
#define mp make_pair
#define SZ(x) x.size()
#define rep(i,a,b) for(int i=a;i<b;i++)
#define per(i,a,b) for(int i=b-1;i>=a;i--)
#define pi acos(-1)
#define mod 1000000007
#define inf 1000000007
#define ll long long
#define DBG(x) cerr<<(#x)<<"="<<x<<"\n";
#define N 200010
template <class U,class T> void Max(U &x, T y){if(x<y)x=y;}
template <class U,class T> void Min(U &x, T y){if(x>y)x=y;}
template <class T> void add(int &a,T b){a=(a+b)%mod;}
int gcd(ll a,ll b){
return b==0 ? abs(a): gcd(b,a%b);

}
int main()
{
    ll n,a,b,ans,sum1=0,sum2=1;
    scanf("%lld",&n);
    for(int i=0;i<n;i++)
    {
       scanf("%lld/%lld",&a,&b);
       ans=gcd(a,b);
       a=a/ans;
       b=b/ans;
       sum1=a*sum2+b*sum1;
       sum2=b*sum2;
       ans=gcd(sum1,sum2);
       sum1=sum1/ans;
       sum2=sum2/ans;
    }

    ll res=sum1/sum2;
    sum1=sum1-(sum2*res);
    if(res!=0)
    {
        cout<<res;
        if(sum1!=0)cout<<" ";
    }
    if(sum1!=0)
    {
        printf("%lld/%lld",sum1,sum2);
    }
    if(res==0&&sum1==0)
        printf("0");
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值