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

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;
}
相关推荐
June`6 分钟前
专题四:综合练习( 找出所有子集的异或总和再求和)
c++·算法·深度优先·剪枝
越甲八千10 分钟前
windowsC++操作ADB
c++·windows·adb
孞㐑¥11 分钟前
Linux之进程控制
linux·开发语言·c++·经验分享·笔记
Magnum Lehar18 分钟前
3d游戏引擎的Utilities模块实现下
c++·算法·游戏引擎
一丝晨光24 分钟前
数值溢出保护?数值溢出应该是多少?Swift如何让整数计算溢出不抛出异常?类型最大值和最小值?
java·javascript·c++·rust·go·c·swift
JANYI201833 分钟前
C语言易混淆知识点详解
java·c语言·算法
愚润求学35 分钟前
【Linux】简单设计libc库
linux·运维·开发语言·c++·笔记
刚入坑的新人编程40 分钟前
C++STL——map和set的使用
开发语言·c++
洛克希德马丁1 小时前
QLineEdit增加点击回显功能
c++·qt·ui
Darkwanderor1 小时前
c++STL-list的使用和迭代器
c++·list