日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

1081 Rational Sum (20 分)_22行代码AC

發布時間:2024/2/28 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 1081 Rational Sum (20 分)_22行代码AC 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

立志用最少的代碼做最高效的表達


PAT甲級最優題解——>傳送門


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,也就是2322^{32}232,考慮無優化的分數相加方法,即分母相乘分子同分后相加。分母相乘不會超過2642^{64}264也就是不會超過long long的取值范圍。 因此可以考慮采用暴力循環方式求解(20分的題應該也沒啥數據結構)

具體算法邏輯見代碼。

分數運算類型題常見模板:
1、采用pair存儲分子和分母,初始化值為 (0, 1)
2、分母相乘,分子通分后相加, 最后利用最大公約數約分。


#include<bits/stdc++.h> using namespace std; using gg = long long;gg gcd(gg a, gg b) { return (b == 0 ? a : gcd(b, a%b)); } //約分過程中無需考慮分子為0的因素。 int main() {gg N; scanf("%lld", &N);//分數初始化后, 分子是0,分母是1 pair<gg, gg>f, sum({0,1}); //一個儲存分子,一個儲存分母 while(N--) {scanf("%lld/%lld", &f.first, &f.second);sum.first = sum.first*f.second + sum.second*f.first;sum.second *= f.second;gg k = gcd(sum.first, sum.second);sum.first /= k;sum.second /= k; }gg k = sum.first/sum.second;sum.first %= sum.second;if(k!=0 && sum.first!=0) printf("%lld %lld/%lld", k, sum.first, sum.second);else if(k==0 && sum.first != 0) printf("%lld/%lld", sum.first, sum.second);else printf("%lld", k);return 0; }

耗時


求贊哦~ (?ω?)

總結

以上是生活随笔為你收集整理的1081 Rational Sum (20 分)_22行代码AC的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。