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

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 分钟前
java后端工程师+AI大模型开发进修ing(研一版‖day61)
java·开发语言·学习·算法·语言模型
2301_803554524 分钟前
Qt禁止子线程直接操作GUI
c++
Cx330❀15 分钟前
Git 基础操作通关指南:版本回退、撤销修改与文件删除深度解析
大数据·运维·服务器·git·算法·搜索引擎·面试
前端小白在前进17 分钟前
力扣刷题:合并两个有序数组
算法·leetcode·职场和发展
羑悻的小杀马特23 分钟前
C++与Redis高效交互:通过optional与迭代器玩转String/List/Set......,打造高性能存储方案!
c++·redis·交互
john_hjy35 分钟前
标量、向量、矩阵、张量
算法·机器学习·矩阵
+++.37 分钟前
c++雪花屏(vsCode+cmake+mingw+ninja)
开发语言·c++·vscode
qq_4308558840 分钟前
线代第一章行列式第八课:克莱姆法则(Cramer法则)
线性代数·算法·矩阵
小妖66641 分钟前
力扣(LeetCode)- 542. 01 矩阵
算法·leetcode·矩阵
小年糕是糕手42 分钟前
【C++】内存管理(下)
java·c语言·开发语言·数据结构·c++·算法