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

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;
}
相关推荐
岛雨QA1 分钟前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc1 分钟前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
铸人2 分钟前
大数分解的Shor算法-C#
开发语言·算法·c#
问好眼5 分钟前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛
yyjtx5 分钟前
DHU上机打卡D31
开发语言·c++·算法
GEO行业研究员5 分钟前
《认知锚定与路径锁死:基于爱搜光年模型的AI决策链条风险放大机制监测》
人工智能·算法·ai搜索优化·geo优化·医疗geo·医疗geo优化
wefg19 分钟前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA16 分钟前
图「Java数据结构与算法学习笔记12」
数据结构·算法
czxyvX22 分钟前
020-C++之unordered容器
数据结构·c++
岛雨QA23 分钟前
多路查找树「Java数据结构与算法学习笔记11」
数据结构·算法