PAT_A1081 Rational Sum

发布时间 2023-10-29 11:06:17作者: 永无荒城

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<bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node{
	ll a, b;
};
int gcd(int a, int b){
	return b ? gcd(b, a%b):a;
}
node myadd(node a, node b){
	ll q = a.a*b.b + b.a*a.b;
	ll w = a.b * b.b;
	ll d = gcd(q, w);
	d = d<0 ? -d : d;
	a.a = q/d;
	a.b = w/d;
	return a;
}
node r, t;
int main(){
	r.a=0; r.b=1;
	ll n; scanf("%lld", &n);
	for(ll i = 0; i < n; i++){
		ll a,b,d;
		scanf("%lld/%lld", &a, &b);
		d = gcd(a, b);
		d = d<0 ? -d : d;
		t.a = a/d;
		t.b = b/d;
		r = myadd(r, t);
	}
	if(abs(r.a) >= r.b)
		r.a%r.b==0 ? printf("%lld", r.a/r.b) : printf("%lld %lld/%lld", r.a/r.b, r.a%r.b, r.b);
	else
		r.a == 0 ? printf("0") : printf("%lld/%lld", r.a, r.b);
	return 0;
}

总结
1、 #分数 本题主要考察分数的运算,和分数的输出
2、数据范围为int,但两分母相乘时,最大可达到long long,应该用long long
3、测试点4会检查0的输出
4、[[分数及其运算模板]]