1081. Rational Sum (20)
来源:互联网 发布:淘宝首页全屏怎么装修 编辑:程序博客网 时间:2024/05/18 00:56
题目链接:https://www.patest.cn/contests/pat-a-practise/1081
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
注意点:数据范围为int,当两个分母相乘时,最大可以达到long long,所以如果使用int就会溢出,有一个测试点错误
#include<cstdio>#include<algorithm>using namespace std;typedef long long ll;const int maxn=110;ll a[maxn],b[maxn];//分别存放分子数组,分母数组 ll gcd(ll x,ll y){//求最大公约数 if(y==0) return x; else return gcd(y,x%y);}int main(){ int n; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%lld/%lld",&a[i],&b[i]); } ll x=b[0]; for(int i=1;i<n;i++){//求分母数组的最小公倍数 x=x*b[i]/gcd(x,b[i]); } for(int i=0;i<n;i++){ a[i]=a[i]*(x/b[i]); } ll ans1=0,ans2; for(int i=0;i<n;i++){ ans1+=a[i]; } ll t=gcd(abs(ans1),abs(x)); ans1/=t,ans2=x/t;// printf("%d %d\n",ans1,ans2); if(ans2==1){ printf("%d\n",ans1); }else if(abs(ans1)>ans2){ printf("%lld %lld/%lld\n",ans1/ans2,abs(ans1%ans2),ans2); }else{ printf("%lld/%lld\n",ans1,ans2); } return 0; }
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 1081. Rational Sum (20)
- 从jvm的角度来看java的多线程
- 题目1085:求root(N, k)
- Some day some time we will do
- 十八条微信官方关于小程序的精选问答都在这了
- 【Codeforces 724 D Dense Subsequence】+ 贪心
- 1081. Rational Sum (20)
- Mac与Phy组成原理的简单分析
- java基础之网络编程
- express的router.js源码分析
- HDU 2045 不容易系列之(3)—— LELE的RPG难题 【递推】
- 早该开始了,现在正好,与bug斗,与坑斗,其乐无穷!
- 1008: FBI树
- Const Buffer,Texture Buffer
- Effective Java读书笔记七:泛型(部分章节需要重读)