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

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;
}
相关推荐
u01092727110 分钟前
C++与人工智能框架
开发语言·c++·算法
EmbedLinX13 分钟前
嵌入式Linux C++常用设计模式
linux·c++·设计模式
挖矿大亨18 分钟前
C++中空指针访问成员函数
开发语言·c++
Fleshy数模20 分钟前
从欠拟合到正则化:用逻辑回归破解信用卡失信检测的召回率困境
算法·机器学习·逻辑回归
im_AMBER26 分钟前
Leetcode 111 两数相加
javascript·笔记·学习·算法·leetcode
TracyCoder12329 分钟前
LeetCode Hot100(21/100)——234. 回文链表
算法·leetcode·链表
txinyu的博客34 分钟前
解析muduo源码之 Socket.h & Socket.cc
c++
可涵不会debug38 分钟前
Redis魔法学院——第四课:哈希(Hash)深度解析:Field-Value 层级结构、原子性操作与内部编码优化
数据库·redis·算法·缓存·哈希算法
阿猿收手吧!40 分钟前
【C++】模板偏特化与std::move深度解析
服务器·c++
@––––––42 分钟前
力扣hot100—系列1
算法·leetcode·职场和发展