当前位置:网站首页>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;
}
边栏推荐
- JVM之TLAB
- Sublime Text3 set to run your own makefile
- Signal works: time varying and time invariant
- Gmail:如何快速将邮件全部已读
- C语言实现一种创建易管理易维护线程的方法
- LiferayPortal JSONWS反序列化漏洞(CVE-2020-7961)分析
- Caused by: org.apache.xerces.impl.io.MalformedByteSequenceException: Invalid byte 3 of 3-byte UTF-8
- manacher
- Alibaba cloud firewall configuration, multiple settings (iptables and firewall)
- Community Union
猜你喜欢
随机推荐
完美二叉树、完全二叉树、完满二叉树
图片验证码控件
Middle order traversal of Li Kou 94 binary tree
2019.11.17训练总结
Pointer functions and function pointers
Flutter 基础组件之 Text
指针函数和函数指针
FreeRTOS(八)——时间管理
Force deduction 85 question maximum rectangle
山科 的C语言2018练习题(电信)
RecyclerView刷新闪烁与删除Item时崩溃问题
聊聊你理解的线程与并发
Leetcode MySQL database topic 177
容器
Codeforces Round #645 (Div. 2)
Is flush stock trading software reliable and safe?
Codeforces - 1151b thinking
2020-09-21 Visual Studio头文件和库目录配置
EDA and VHDL question bank
2019.10.16训练总结








