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 (≤), 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<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
struct Fraction{
ll up,dowm;
}; ll gcd(ll a,ll b){
return b == ? a : gcd(b,a%b);
} Fraction reduction(Fraction result){
if(result.dowm < ){
result.up = - result.up;
result.dowm = - result.dowm;
}
if(result.up == ){
result.dowm = ;
}else{
int d = gcd(abs(result.dowm),result.up);
result.dowm /= d;
result.up /= d;
}
return result;
} Fraction add(Fraction f1,Fraction f2){
Fraction result;
result.up = f1.dowm*f2.up + f2.dowm*f1.up;
result.dowm = f1.dowm*f2.dowm;
return reduction(result);
} void showResult(Fraction r){
reduction(r);
if(r.dowm == ) printf("%lld",r.up);
else if(abs(r.up) > abs(r.dowm)){
printf("%lld %lld/%lld",r.up/r.dowm,r.up%r.dowm,r.dowm);
}else{
printf("%lld/%lld",r.up,r.dowm);
}
} int main(){
int n;
scanf("%d",&n);
Fraction sum,temp;
sum.up = , sum.dowm = ;
for(int i = ; i < n; i++){
scanf("%lld/%lld",&temp.up,&temp.dowm);
sum = add(sum,temp);
}
showResult(sum);
return ;
}

最新文章

  1. Javascript、Jquery获取浏览器和屏幕各种高度宽度
  2. [LeetCode] Remove Linked List Elements
  3. ssh升级
  4. sobel算子原理及opencv源码实现
  5. Windows Live Writer技巧
  6. 第四章 跨平台图像显示库——SDL 第一节 与SDL第一次亲密接触
  7. OkHttpUtils
  8. mybatis-generator-core自动生成do、mapping、dao 代码
  9. 数据结构——HDU1312:Red and Black(DFS)
  10. linux下ssh使用和配置
  11. strut1.X和spring整合的二种方法
  12. 3D Touch开发
  13. 201521123039 《java程序设计》第九周学习总结
  14. 在MAC OS X中默认的Web共享目录
  15. Scala集合Map
  16. [UE4]Event Tick
  17. IDEA文件对比
  18. docker入门 什么是docker? 为什么使用docker?
  19. C# 分支语句 练习题(中间变量,随机数)
  20. [csp-201509-3]模板生成系统

热门文章

  1. 国画经典之梅花PSD素材
  2. linkedhashSet和hashSet和TreeSet的区别(转)
  3. &lt;%!%&gt;声明的变量和在&lt;%%&gt;中声明的变量的区别
  4. 剑指offer12 打印从1到N位的所有数字,处理大整数情况
  5. CodeForces - 613D:Kingdom and its Cities(虚树+DP)
  6. MySQL11月16-11月21日活动赠送的优惠券使用率_20161124
  7. 搭建基于Nagios的监控系统——之监控远程Linux服务器
  8. bzoj4176
  9. Windows窗体间的数据交互
  10. 虚拟机中的Linux安装VMware&amp;nbsp;Tools