[PAT A1081]Rational Sum
题目描述
1081 Rational Sum (20 分)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.
输入样例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
解析
题目是关于分式的运算,这类型题目是很简单的,但问题就是在于需要有一个传统的定式来解决这一系列问题,所以详情可以移步至,我会在里面写摘要一些关于分式的解法定义(来源于《算法笔记》),我会在里面详细的讲一些注释
工欲善其事必先利其器——盘点PAT中非常好用的工具(持续更新)
#include<iostream>
using namespace std;
struct Fraction {
long long up, down;
};
long long gcd(long long a, long long b)
{
return !b ? a : gcd(b, a%b);
}
Fraction reduction(Fraction f)
{
if (f.down < 0) {
f.up = -f.up;
f.down = -f.down;
}
if (f.up == 0) f.down = 1;
else {
long long t = gcd(abs(f.up), abs(f.down));
f.up = f.up / t;
f.down = f.down / t;
}
return f;
}
void show(Fraction f) {
reduction(f);
if (f.down == 1) printf("%lld", f.up);
else if (abs(f.up) > abs(f.down)) {
printf("%lld %lld/%lld", f.up / f.down, abs(f.up) % abs(f.down), f.down);
}
else printf("%lld/%lld", f.up, f.down);
}
int main()
{
int n;
Fraction f = { 0,1 };
scanf("%d", &n);
for (int i = 0; i < n; i++) {
long long up, down;
scanf("%lld/%lld", &up, &down);
f.up = f.up*down + f.down*up;
f.down = f.down*down;
f=reduction(f);
}
show(f);
return 0;
}