当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

A method of creating easy to manage and maintain thread by C language

KDevelop new project

JVM之方法的绑定机制

JVM之对象的内存布局

JVM之虚拟机栈之动态链接

Automatic Multi-Organ SegmVentation on Abdominal CT With Dense V-Networks

使用Rancher搭建Kubernetes集群

Application of decorator mode, packaging ServletRequest and adding addparameter method

容器

520 钻石争霸赛 2021
随机推荐
2020-09-23左右值 右值引用 std::move()
JNI. H description
Application of decorator mode, packaging ServletRequest and adding addparameter method
Minorgc, majorgc, fullgc
Reverse thinking - short story
逆向思维-小故事
在Activity外使用startActivity()方法报错原因与解决办法
Shanke's C language 2018 exercise (Telecom)
语言特性
RecyclerView刷新闪烁与删除Item时崩溃问题
JVM instructions for four call methods
GSOAP example - calc
Leetcode MySQL database topic 181
Automatic Multi-Organ SegmVentation on Abdominal CT With Dense V-Networks
51nod1277 字符串中的最大值【KMP】
Community Union
Gmail: how to quickly read all messages
Codeforces Round #645 (Div. 2)
Sixteen system counter and flow lamp
聊聊你理解的线程与并发