1081 Rational Sum (20 分)
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<bits/stdc++.h> using namespace std; typedef long long ll; // a/a1 + b/b1 ll to_int(string s){ ll sum = 0; bool flag = 1; if(s[0] == '-'){ flag = 0; s = s.substr(1,s.size()-1); } for(int i=0;i < s.size();i++){ sum = sum*10 + (s[i]-'0'); } if(flag) return sum; else return -sum; } ll gcd(ll x,ll y){ return y?gcd(y,x%y):x; } // a/a1 + b/b1 int main(){ int t;cin >> t; ll a = 0,a1 = 1; while(t--){ string s; cin >> s; int pos = s.find('/'); string stra = s.substr(0,pos); string stra1 = s.substr(pos+1,s.size()-pos); ll b = to_int(stra); ll b1 = to_int(stra1); ll c = a*b1 + b*a1; ll c1 = a1*b1; ll t = gcd(c,c1); a = c/t; a1 = c1/t; } ll x = a/a1; ll y = a%a1; if(x&&y){printf("%lld %lld/%lld",x,y,a1);} else if(!x&&y){printf("%lld/%lld",y,a1);} else if(x&&!y)printf("%lld",x); else printf("0"); return 0; }
——一开始把输出写错了。。