【题解搬运】PAT_L1-009 N个数求和
来源:互联网 发布:mysql engine=myisam 编辑:程序博客网 时间:2024/06/05 08:14
从我原来的博客上搬运。原先blog作废。 (伪)水题+1,旨在继续摸清这个blog(囧
题目
就是求N个数字的和。麻烦的是,这些数字是以有理数“分子/分母”的形式给出的,你输出的和也必须是有理数的形式。
题解
对读入,可以使用scanf(“%d/%d”,…);来解决读入问题(scanf很强的!
然后以为自己稳了。。。结果TLE了
问题在哪里呢?在gcd那里,我一开始加上了b与a的大小判断,然而其实不应该这么做!这样做破坏了尾递归(让gcc没法优gao化shi了),极大的减慢了gcd的速度。
后来删掉了if,引出了个WA2333
问题在于负数分数的问题,处理如下,在两个地方加以处理了。
水题想搞事也很容易啊,大意要不得。
代码
#include <bits/stdc++.h>using namespace std;#define f1(x,y) for(int x=1;x<=y;++x)#define f0(x,y) for(int x=0;x!=y;++x)#define bf1(x,y,z) for(int x=y;x>=z;--x)#define bf0(x,y,z) for(int x=y;x!=z;--x)typedef long long ll;typedef unsigned long long ull;int gcd(int a,int b){// if(b>a) swap(a,b); return (b==0)?a:(gcd(b,a%b));}int lcm(int a,int b){ return a/gcd(a,b)*b;}int main(){ int n; scanf("%d",&n); int tota,totb; f1(i,n) { int a,b; scanf("%d/%d",&a,&b); if(i==1) { tota=a;totb=b; } else { int tmpb=b; tmpb=lcm(b,totb); tota=tota*tmpb/totb+a*tmpb/b; totb=tmpb; } int g=gcd(abs(tota),abs(totb)); tota/=g;totb/=g; //cout<<tota<<" "<<totb<<endl; } if(abs(tota)>=abs(totb) || tota==0) { printf("%d",tota/totb); if(tota%totb==0) printf("\n"); else printf(" %d/%d\n",abs(tota)%abs(totb),totb); } else printf("%d/%d\n",tota,totb); //printf("%d/%d\n",tota,totb); return 0;}
阅读全文
0 0
- 【题解搬运】PAT_L1-009 N个数求和
- 天梯赛-L1-009-N个数求和
- 任意n个数求和
- N个数求和
- N个数求和
- N个数求和
- N个数求和
- N个数求和
- PAT N个数求和
- 1039: n个数求和
- 任意前n个数求和
- 1~n 个数叠加求和
- L1-009. N个数求和
- L1-009. N个数求和
- L1-009. N个数求和
- L1-009. N个数求和
- L1-009. N个数求和
- L1-009. N个数求和
- 2017派卧底去阿里、京东、美团、滴滴带回来的面试题及答案
- 使用聚合函数查询
- chown和chomd 具体用法,不讲费话
- Windows解决删除文件权限不够问题
- 【UI设计】1、Material Design概述
- 【题解搬运】PAT_L1-009 N个数求和
- 物理隔离
- XListView基础使用
- SpringCloud-Eureka(三)常见问题
- Azure VPN 支持 BGP 的实现
- 图解https
- 题目:利用嵌套条件运算符来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示
- android清除缓存,查看缓存
- 实时监控、直播流、流媒体、视频网站开发方案流媒体服务器搭建及配置详解:使用nginx搭建rtmp直播、rtmp点播、,hls直播服务配置详解