我是一个小菜鸡,从来也不放弃努力

Rational Sum (20)
时间限制 1000 ms 内存限制 65536 KB 代码长度限制 100 KB 判断程序 Standard (来自 小小)
题目描述
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.

输入例子:
5
2/5 4/15 1/30 -2/60 8/3

输出例子:
3 1/3
#include<cstdio>
#include<iostream>
using namespace std;
int n, a, b,c,d;
int gcd(int x, int y)
{
	return y == 0 ? x : gcd(y, x%y);
}
int lcm(int x, int y)
{
	return x / gcd(x, y)*y;
}
int main()
{
	cin >> n;
	scanf("%d/%d", &a, &b);
	for (int i = 1; i < n; i++)
	{
		scanf("%d/%d", &c, &d);
		int lc = lcm(b, d);
		a = (lc / b*a + lc / d*c);
		b = lc;
	}
	
	//cout << a << endl; cout << b << endl;
	int tt = gcd(a, b);// cout << tt << endl;
	a /= tt, b /= tt;
	//格式输出弄了半天,需要注意。把所以可能的情况都举个小栗子,然后分类讨论
	if (a!=0){
		if ((a / b) != 0){
			if ((a/b) > 0)
				printf("%d %d/%d\n", a / b, a%b, b);
			else
			{
				if ((a%b)!=0)
					printf("%d %d/%d\n", a / b,-(a%b) , b);
				else
					printf("%d\n", a / b);
			}
		}
		else{
			if (a*b > 0){
				printf("%d/%d\n",  a, b);
			}else
				printf("-%d/%d\n", (a<0?-a:a),(b<0?-b:b));

		}

		
	}
	else
		printf("%d\n", a);
	//cout << (-10 / 3) << endl; cout << (-10 % 3) << endl;
	system("pause");
	return 0;
}
全部评论

相关推荐

美丽的查理斯不讲武德:包kpi的啊,感觉虾皮一点hc都没有
点赞 评论 收藏
分享
2 收藏 评论
分享
牛客网
牛客企业服务