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

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;
}
相关推荐
小wanga8 分钟前
【leetcode_C++_string】387.字符串中的第一个唯一字符
c++·算法·leetcode
Cancan200418 分钟前
栈和队列讲解
数据结构·算法
枯藤老树周黑鸭28 分钟前
日常刷题(24)
数据结构·python·算法
Blasit33 分钟前
QT C++ 判断字符串是否是一个数字
开发语言·c++·qt·正则表达式
sz66cm1 小时前
数学基础 -- 线性代数之向量基本概念
线性代数·算法·机器学习
孤寂大仙v1 小时前
C&C++内存管理
java·c语言·c++
桃酥4031 小时前
算法day16(补第15天)|用递归方法求解:513.找树左下角的值
数据结构·c++·算法·leetcode
qwq!61 小时前
虚幻5|(1)技能栏快捷格子的制作|(2)如何在游戏进行的时候显示鼠标,使用鼠标操作UI||(3)改进技能释放
c++·笔记·游戏·ui·ue5·虚幻·虚幻引擎
国中之林2 小时前
【C++ Primer Plus习题】7.1
开发语言·c++·学习·刷题
Tai_Monster2 小时前
最长回文子串:动态规划推导
算法·动态规划·代理模式