浙江财经大学
信工学院ACM集训队

PAT(A) 1081. Rational Sum (20)

本文由 Ocrosoft 于 2016-12-28 21:25:02 发表

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 <set>
#include <map>
#include <list>
#include <cmath>
#include <stack>
#include <queue>
#include <ctime>
#include <string>
#include <cstdio>
#include <vector>
#include <cctype>
#include <climits>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <functional>
#define strend string::npos
#define ms(a) memset(a,0,sizeof(a))
#define  rep(a,v,b) for(int a=v;a<b;a++)
#define  repe(a,v,b) for(int a=v;a<=b;a++)
typedef long long LL;
const LL LINF = LLONG_MAX / 2;
const int INF = INT_MAX / 2;
const int MAXN = 300000 + 10;
const int MOD = 1000000009;
LL GCD(LL a, LL b)
{
	if (!b)return a;
	return GCD(b, a%b);
}
/*(◕‿‿◕) (◕‿‿◕) (◕‿‿◕) (◕‿‿◕) (◕‿‿◕)*/
/*(◕‿‿◕) 签订契约,成为马猴烧酒吧! (◕‿‿◕)*/
/*(◕‿‿◕) (◕‿‿◕) (◕‿‿◕) (◕‿‿◕) (◕‿‿◕)*/
using namespace std;
struct rational
{
	LL a, b;
	void add(rational other)
	{
		LL lcm = b*other.b / GCD(b, other.b);
		a *= lcm / b;
		a += other.a*(lcm / other.b);
		b = lcm;
		LL gcd = GCD(a, b);
		if (gcd != 1)a /= gcd, b /= gcd;
	}
	void print()
	{
		if (!a) { printf("0\n"); return; }
		if (a >= b)
		{
			printf("%lld", a / b);
			if (a%b)printf(" %lld/%lld\n", a%b, b);
			else printf("\n");
		}
		else printf("%lld/%lld\n", a, b);
	}
};
int main()
{
	rational x, y;
	int n; cin >> n;
	scanf("%lld/%lld", &x.a, &x.b);
	rep(i, 1, n)
	{
		scanf("%lld/%lld", &y.a, &y.b);
		x.add(y);
		//x.print();
	}
	x.print();
	return 0;
}

欢迎转载,请保留出处与链接。Ocrosoft » PAT(A) 1081. Rational Sum (20)

点赞 (0)or拍砖 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址