pat-a1081. Rational Sum (20)

来源:互联网 发布:葛底斯堡演说 知乎 编辑:程序博客网 时间:2024/06/10 18:06

以前做这种题没有用struct。。两个int相乘不会超过long long。。以前还是先约分再加的。。可以直接加了再约分。

#include<cstdio>typedef long long int LL;struct node{LL fenz,fenm;node(LL a=0,LL b=1):fenz(a),fenm(b){}};LL gcd(LL a,LL b){if(b==0) return a;return gcd(b,a%b);}void add(node& sum,const node& t){sum.fenz=sum.fenz*t.fenm+sum.fenm*t.fenz;sum.fenm=sum.fenm*t.fenm;LL k=gcd(sum.fenz,sum.fenm);sum.fenz/=k;sum.fenm/=k;}int main(){int n;node sum(0,1);LL a,b;scanf("%d",&n);while(n--){scanf("%lld/%lld",&a,&b);node temp(a,b);add(sum,temp);}int t=sum.fenz/sum.fenm;if(t*sum.fenm==sum.fenz) printf("%d\n",t);else{sum.fenz=sum.fenz%sum.fenm;if(sum.fenz<0){printf("-");sum.fenz=-sum.fenz;}if(t!=0) printf("%d ",t);if(sum.fenz) printf("%lld/%lld\n",sum.fenz,sum.fenm);}return 0;}

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:
52/5 4/15 1/30 -2/60 8/3
Sample Output 1:
3 1/3
Sample Input 2:
24/3 2/3
Sample Output 2:
2
Sample Input 3:
31/3 -1/6 1/8

0 0