PTA Rational Sum (20分)

释放无限光明的是人心,制造无边黑暗的也是人心,光明和黑暗交织着,厮杀着,这就是我们为之眷恋又万般无奈的人世间。

Given N rational numbers in the form numerator/denominator, you are supposed to calculate their sum.

Input Specification:

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.

Output Specification:

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.

Sample Input 1:

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

Sample Output 1:

3 1/3

Sample Input 2:

2
4/3 2/3

Sample Output 2:

2

Sample Input 3:

3
1/3 -1/6 1/8

Sample Output 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