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

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 分钟前
嵌入式工程师一年制深度进阶学习计划(纯技术深耕版)
linux·运维·服务器·c语言·数据库·算法
-To be number.wan7 分钟前
【数据结构真题解析】哈希表高级挑战:懒惰删除、探测链断裂与查找正确性陷阱
数据结构·算法·哈希算法
CSDN_RTKLIB9 分钟前
【std::string】find函数
c++·stl
历程里程碑10 分钟前
哈希2:字母异位符分组
算法·leetcode·职场和发展
十五年专注C++开发14 分钟前
浅谈CPU中的SIMD
c++·cpu·代码优化·simd
AI科技星21 分钟前
统一场论理论下理解物体在不同运动状态的本质
人工智能·线性代数·算法·机器学习·概率论
txinyu的博客22 分钟前
sprintf & snprintf
linux·运维·算法
pas13627 分钟前
34-mini-vue 更新element的children-双端对比diff算法
javascript·vue.js·算法
Qhumaing28 分钟前
数据结构——例子求算法时间复杂度&&空间复杂度
数据结构·算法
Yu_Lijing34 分钟前
基于C++的《Head First设计模式》笔记——状态模式
c++·笔记·设计模式