码迷,mamicode.com
首页 > 其他好文 > 详细

1081. Rational Sum (20)

时间:2015-02-13 18:12:39      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

 

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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


 1 #include<stdio.h>
 2 #include<vector>
 3 #include<math.h>
 4 #include<cmath>
 5 using namespace std;
 6 
 7 int getGCD(long long a,long long b)
 8 {
 9 while(b!=0)
10 {
11 int t = a % b;
12 a = b ;
13 b = t ;
14 }
15 
16 return a;
17 }
18 int main()
19 {
20 int n,i;
21 long long tem1,tem2;
22 scanf("%d",&n);
23 vector<long long> child,mother;
24 for(i = 0; i < n ;i ++)
25 {
26 
27 scanf("%lld/%lld",&tem1,&tem2);
28 child.push_back(tem1);
29 mother.push_back(tem2);
30 }
31 
32 long long MonSum = 1;
33 long long ChildSum = 0;
34 long long tem ;
35 for(i = 0; i < mother.size() ;i++)
36 {
37 ChildSum = mother[i]*ChildSum + MonSum*child[i];
38 MonSum *= mother[i];
39 tem = getGCD(abs(MonSum) , abs(ChildSum));
40 ChildSum = ChildSum / tem;
41 MonSum = MonSum / tem;
42 }
43 
44 
45 long long pre;
46 
47 pre = ChildSum/MonSum;
48 ChildSum = ChildSum % MonSum;
49 tem = getGCD(abs(MonSum) , abs(ChildSum));
50 ChildSum = ChildSum / tem;
51 MonSum = MonSum / tem;
52 if(ChildSum == 0)
53 {
54 printf("%lld\n",pre);    
55 }
56 else if( ChildSum != 0 && pre == 0)
57 {
58 printf("%lld/%lld\n",ChildSum,MonSum);
59 }
60 else if( ChildSum != 0 && pre != 0)
61 {
62 printf("%lld ",pre);    
63 printf("%lld/%lld\n",ChildSum,MonSum);
64 }
65 
66 
67 return 0;
68 }

 

1081. Rational Sum (20)

标签:

原文地址:http://www.cnblogs.com/xiaoyesoso/p/4290479.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!