PAT甲级 A1081
题目详情
1081 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
解题思路
这道题通过率低,就是因为它的溢出问题。原本的策略是每次读入数据分式相加,然后进行约分,这样会产生溢出。需要读入数据时进行约分 再相加,再约分(还需要判断非0)
以下为AC代码
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<algorithm>
#include<map>
#include<vector>
#include<iomanip>
#include<queue>
#include<cmath>
using namespace std;
long long int publicnumber(int a, int b) {
a = abs(a);
b = abs(b);
if (a == b) {
return a;
}
else if (a<b) {
int temp = a;
a = b;
b = temp;
}
if (a % b == 0) {
return b;
}
for (int i = int(sqrt(b)); i >= 2; i--) {
if (a % i == 0 && b % i == 0) {
return i;
}
}
return -5;
}
int main(){
int N; cin >> N;
if (N == 0) {
cout << 0 << '\n';
return 0;
}
char emptys;
long long int num = 0; long long int den = 0;
for (int i = 0; i < N; i++) {
if (i == 0) {
scanf_s("%lld", &num);
scanf_s("%c", &emptys);
scanf_s("%lld", &den);
if (num != 0) {
long long int pbs = publicnumber(num, den);
if (pbs != -5) {
num = num / pbs; den = den / pbs;
}
}
else {
num = 0;
den = 1;
}
continue;
}
else {
long long int n1; long long int den1;
scanf_s("%lld", &n1);
scanf_s("%c", &emptys);
scanf_s("%lld", &den1);
if (n1 != 0) {
long long int pbs = publicnumber(n1, den1);
if (pbs != -5) {
n1 = n1 / pbs; den1 = den1 / pbs;
}
}
else {
n1 = 0; den1 = 1;
}
long long int big = den1*den;
long long int temp1 = n1 * den;
long long int temp2 = num * den1;
num = temp1 + temp2; den = big;
if (num == 0) {
den = 1;
continue;
}
long long int pb = publicnumber(num, den);
if (pb == -5) {
continue;
}
else {
num = num / pb; den = den / pb;
}
}
}
long long int mat = abs(num) / den; long long int left = abs(num) % den;
if (mat != 0 && left == 0) {
if (num < 0) {
cout << '-';
}
cout << mat << '\n';
}
else if (mat == 0 && left == 0) {
cout << 0 << '\n';
}
else if(mat!=0&&left!=0){
if (num < 0) {
cout << '-';
}
cout << mat << " ";
}
if (left != 0) {
long long int pb = publicnumber(left, den);
if (pb != -5) {
left = left / pb; den = den / pb;
}
if (num < 0) {
cout << '-';
}
cout << left << '/' << den << '\n';
}
}