标签:front map printf cat temp lin cti down next
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
2
4/3 2/3
2
3
1/3 -1/6 1/8
7/24
思路
先加再化简
#include<iostream> #include<vector> #include<algorithm> #include<map> #include<set> #include<cmath> #include<climits> #include<sstream> #include<cstdio> #include<string.h> #include<unordered_map> using namespace std; struct Fraction { int up; int down; }; int gcd(int a,int b) { if(b==0) return a; return gcd(b,a%b); } void reduction(Fraction &temp) { if(temp.up==0) temp.down=1; int t=gcd(abs(temp.up),temp.down); temp.up/=t; temp.down/=t; } void add(Fraction &sum,Fraction &temp) { sum.up=sum.up*temp.down+sum.down*temp.up; sum.down=sum.down*temp.down; reduction(sum); } int main() { int n; scanf("%d",&n); Fraction sum,temp; for(int i=0;i<n;i++) { scanf("%d/%d",&temp.up,&temp.down); if(i==0) sum=temp; else add(sum,temp); } int it=sum.up/sum.down; if(it>0) { printf("%d",it); sum.up=sum.up%sum.down; if(sum.up!=0) printf(" %d/%d",sum.up,sum.down); return 0; } if(sum.up==0) printf("0"); else printf("%d/%d",sum.up,sum.down); return 0; }
标签:front map printf cat temp lin cti down next
原文地址:https://www.cnblogs.com/zhanghaijie/p/10348222.html