当前位置:网站首页>L1-009 N个数求和 (20 分)
L1-009 N个数求和 (20 分)
2022-06-29 09:23:00 【陌陌623】
L1-009 N个数求和 (20 分)
本题的要求很简单,就是求N个数字的和。麻烦的是,这些数字是以有理数分子/分母的形式给出的,你输出的和也必须是有理数的形式。
输入格式:
输入第一行给出一个正整数N(≤100)。随后一行按格式a1/b1 a2/b2 ...给出N个有理数。题目保证所有分子和分母都在长整型范围内。另外,负数的符号一定出现在分子前面。
输出格式:
输出上述数字和的最简形式 —— 即将结果写成整数部分 分数部分,其中分数部分写成分子/分母,要求分子小于分母,且它们没有公因子。如果结果的整数部分为0,则只输出分数部分。
输入样例1:
5
2/5 4/15 1/30 -2/60 8/3
输出样例1:
3 1/3
输入样例2:
2
4/3 2/3
输出样例2:
2
输入样例3:
3
1/3 -1/6 1/8
输出样例3:
7/24
题解
记得去年做这个题的时候 用了挺长时间的
今天师弟做这个题,刚才问了,我去给他现场敲。还真,,没敲对hh。不过思路是对的
然后回到我位置上敲了一会出来了。
用一个数,每次都让这个数去加下一个。因为是longlong
所以 求的过程中必须得化简
他们通分的最优分母是 他们的最小公倍数
通分后的分子就是 分子*最小公倍数/分母
#include <iostream>
#include <algorithm>
using namespace std;
const int n = 110;
pair<long long, long long> p[n], res;
int main()
{
int N;
char c;
cin >> N;
for (int i = 0; i < N; i++)
cin >> p[i].first >> c >> p[i].second;
res = p[0];
for (int i = 1; i < N; i++)
{
long long gc = (res.second * p[i].second) / (__gcd(res.second, p[i].second));
res.first = res.first * (gc / res.second) + p[i].first * (gc / p[i].second);
res.second = gc;
long long r = -1;
while (r != 1)
{
r = __gcd(res.second, res.first);
res.second /= r;
res.first /= r;
}
}
if (res.second == 1)
cout << res.first;
else
{
long long t = res.first / res.second;
if (t >= 1)
cout << t << " " << res.first - res.second * t << c << res.second << endl;
else
{
cout << res.first << c << res.second << endl;
}
}
return 0;
}
边栏推荐
猜你喜欢
随机推荐
LiferayPortal JSONWS反序列化漏洞(CVE-2020-7961)分析
Cisco ASA、FTD和HyperFlex HX的漏洞分析复现
Constructing SQL statements by sprintf() function in C language
float 与 int 相乘产生的令人崩溃的“ 2.3 * 10 = 22 ”
Application of decorator mode, packaging ServletRequest and adding addparameter method
Codeforces Round #645 (Div. 2)
Binding mechanism of JVM methods
Alibaba cloud firewall configuration, multiple settings (iptables and firewall)
Flutter 基础组件之 GridView
ImageView图片填充问题
Leetcode MySQL database topic 181
Middle order traversal of Li Kou 94 binary tree
动态规划总结
leetcode MYSQL数据库题目178
KDevelop new project
GCC and makefile
弧形 View 和弧形 ViewPager
Caused by: org. apache. xerces. impl. io. MalformedByteSequenceException: Invalid byte 3 of 3-byte UTF-8
【51nod 1215】数组的宽度
2019.11.3学习总结









