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

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;
}
相关推荐
重庆小透明39 分钟前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
desssq1 小时前
力扣:70. 爬楼梯
算法·leetcode·职场和发展
clock的时钟1 小时前
暑期数据结构第一天
数据结构·算法
小小小小王王王2 小时前
求猪肉价格最大值
数据结构·c++·算法
岁忧2 小时前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go
BIYing_Aurora2 小时前
【IPMV】图像处理与机器视觉:Lec13 Robust Estimation with RANSAC
图像处理·人工智能·算法·计算机视觉
码农编程录3 小时前
【c/c++3】类和对象,vector容器,类继承和多态,systemd,std&boost
c++
martian6654 小时前
支持向量机(SVM)深度解析:从数学根基到工程实践
算法·机器学习·支持向量机
孟大本事要学习4 小时前
算法19天|回溯算法:理论基础、组合、组合总和Ⅲ、电话号码的字母组合
算法
??tobenewyorker5 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode