1081. Rational Sum (20)模拟——PAT (Advanced Level) Practise
Posted 闲云阁
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1081. Rational Sum (20)模拟——PAT (Advanced Level) Practise相关的知识,希望对你有一定的参考价值。
题目信息
1081. Rational Sum (20)
时间限制400 ms
内存限制65536 kB
代码长度限制16000 B
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
解题思路
模拟加法,注意结果中分母负号和分子为0情况
AC代码
#include <cstdio>
struct node{
long long a, b;
node(long long a, long long b):a(a), b(b){}
};
long long gcd(long long a, long long b){
return b ? gcd(b, a%b) : a;
}
node add(node& a, node& b){
node r(a.a*b.b + a.b*b.a, a.b*b.b);
long long t = gcd(r.a, r.b);
r.a /= t;
r.b /= t;
return r;
}
int main()
{
int n;
long long a, b;
scanf("%d", &n);
scanf("%lld/%lld", &a, &b);
node p(a, b);
for (int i = 1; i < n; ++i){
scanf("%lld/%lld", &a, &b);
node t(a, b);
p = add(p, t);
}
if (p.b < 0){
p.b *= -1;
p.a *= -1;
}
if (p.a >= p.b){
printf("%lld", p.a/p.b);
if (p.a % p.b){
printf(" %lld/%lld", p.a%p.b, p.b);
}
}else{
if (p.a == 0){
printf("0");
}else{
printf("%lld/%lld", p.a, p.b);
}
}
printf("\n");
return 0;
}
以上是关于1081. Rational Sum (20)模拟——PAT (Advanced Level) Practise的主要内容,如果未能解决你的问题,请参考以下文章
PAT甲题题解-1081. Rational Sum (20)-模拟分数计算