PTA Rational Sum(20ポイント)

無限の光を放つのは人間の心であり、無限の闇を生み出すのも人間の心であり、光と闇が絡み合って戦うこの世界は、懐かしくて無力な世界です。

形式Nの有理数  numerator/denominatorを指定すると、それらの合計を計算することになります。

入力仕様:

各入力ファイルには1つのテストケースが含まれています。各ケースは正の整数N(≤100)で始まり、次の行ではNの有理数が続きます。  a1/b1 a2/b2 ... ここで、すべての分子と分母はlong intの範囲にあり  ます。負の数がある場合、符号は分子の前に表示する必要があります。

出力仕様:

テストケースごとに、最も単純な形式integer numerator/denominator で  合計を出力します。ここで、は合計  integer の整数部分  numerator <  denominatorであり、分子と分母には共通の因子がありません。整数部分が0の場合、小数部分のみを出力する必要があります。

入力例1:

5
2/5 4/15 1/30 -2/60 8/3

出力例1:

3 1/3

入力例2:

2
4/3 2/3

出力例2:

2

入力例3:

3
1/3 -1/6 1/8

出力例3:

7/24
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <vector>
#include <ctime>
#include <cctype>
#include <bitset>
#include <utility>
#include <sstream>
#include <complex>
#include <iomanip>
#include<climits>//INT_MAX
#define PP pair<ll,int>
#define inf 0x3f3f3f3f
#define llinf 0x3f3f3f3f3f3f3f3fll
#define dinf 1000000000000.0
#define PI 3.1415926
typedef long long ll;
using namespace std;
int const mod=1e9+7;
const int maxn=3e5+10;
struct node
{
    int fz;
    int fm;
};
int gcd(int a,int b)
{
    if(b==0)
        return a;
    return gcd(b,a%b);
}
void hj(node &ls)
{
    if(ls.fz==0)
        ls.fm=1;
    int t=gcd(abs(ls.fz),ls.fm);
    ls.fz/=t;
    ls.fm/=t;
}
void add(node &sum,node &ls)
{
    sum.fz=sum.fz*ls.fm+sum.fm*ls.fz;
    sum.fm=sum.fm*ls.fm;
    hj(sum);
}
int main()
{
    int n;
    node jg,ls;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        scanf("%d/%d",&ls.fz,&ls.fm);
        if(i==0)
            jg=ls;
        else
            add(jg,ls);
    }
    int it=jg.fz/jg.fm;
    if(it>0)
    {
        printf("%d",it);
        jg.fz=jg.fz%jg.fm;
        if(jg.fz!=0)
            printf(" %d/%d",jg.fz,jg.fm);
        return 0;
    }
    if(jg.fz==0)
        printf("0");
    else
        printf("%d/%d",jg.fz,jg.fm);
    return 0;
}

 

おすすめ

転載: blog.csdn.net/weixin_44170305/article/details/108414729