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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【已解决】The server time
- 下一篇: 【简便解法】1084 Broken Ke