【算法/天梯赛训练】天梯赛模拟题集

L1-009 N个数求和

cpp 复制代码
#include <iostream>
#include <algorithm>

using namespace std;

typedef long long ll;
const int N = 105;

typedef struct node {
	ll x, y;
}node;
node a[N];

ll gcd(ll a, ll b)
{
	return b ? gcd(b, a % b) : a;
}

int main()
{
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) scanf("%lld/%lld", &a[i].x, &a[i].y);

	ll ans = a[0].y;
	for (int i = 1; i < n; i++)
	{
		ans = ans / gcd(ans, a[i].y) * a[i].y;
	}
	//printf("%lld\n", ans);
	ll res = 0; //分子和
	for (int i = 0; i < n; i++)
	{
		res = res + ans / a[i].y * a[i].x;
	}
	ll x = res / ans;
	ll b = res % ans;
	ll c = 1;
	if (b != 0)
	{
		c = gcd(b, ans);
		b /= c, ans /= c;
	}
	if (x == 0)
	{
		if (b != 0)printf("%lld/%lld", b, ans);
		else printf("0");
	}
	
	if (b == 0 && x != 0) printf("%lld", x);
	if(x!=0 && b!= 0) printf("%lld %lld/%lld", x, b, ans);
	return 0;
}
相关推荐
艾莉丝努力练剑3 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
_殊途4 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
还债大湿兄4 小时前
《C++内存泄漏8大战场:Qt/MFC实战详解 + 面试高频陷阱破解》
c++·qt·mfc
珊瑚里的鱼7 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上8 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
Risehuxyc8 小时前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
秋说8 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法
lifallen9 小时前
Kafka 时间轮深度解析:如何O(1)处理定时任务
java·数据结构·分布式·后端·算法·kafka
liupenglove9 小时前
自动驾驶数据仓库:时间片合并算法。
大数据·数据仓库·算法·elasticsearch·自动驾驶
python_tty10 小时前
排序算法(二):插入排序
算法·排序算法