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

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;
}
相关推荐
海石20 分钟前
1563分的简单题,可能就简单在能被暴力AC
算法·leetcode
海石30 分钟前
1400分的dp汗流浃背之【交替子数组计数】
算法·leetcode
奋发向前wcx34 分钟前
P2590 树的统计 题目解析
数据结构·算法·深度优先
2023自学中1 小时前
C++ 内存追踪器
linux·c++
imbackneverdie1 小时前
AI4S不止于分子药物:以MedPeer为代表的科研基建打开产业新增量
大数据·人工智能·算法·aigc·科研·学术·ai 4s
额鹅恶饿呃2 小时前
C语言中的数据结构和变量
c语言·数据结构·算法
运行时记录4 小时前
prompt-optimizer skill
算法
万法若空4 小时前
【数据结构-哈希表】哈希表原理
数据结构·算法·散列表
退休倒计时4 小时前
【每日一题】LeetCode 437. 路径总和 III TypeScript
算法·leetcode·typescript
学逆向的4 小时前
汇编——内存
开发语言·汇编·算法·网络安全