1081 Rational Sum

cpp 复制代码
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
struct frac{
    ll up;
    ll down;
};
ll gcd(ll a, ll b){
    if(b == 0){
        return a;
    }
    return gcd(b, a % b);
}

frac reduc(frac a){
    if(a.down < 0){
        a.down = -a.down;
        a.up = -a.up;
    }
    if(a.up == 0){
        a.down = 1;
    }else{
        ll d = gcd(abs(a.up), abs(a.down));
        a.up = a.up / d;
        a.down = a.down / d;
    }
    return a;
}

frac add(frac a, frac b){
    frac res;
    res.down = a.down * b.down;
    res.up = a.up*b.down + b.up*a.down;
    return reduc(res);
}
int main() {
    int n;
    scanf("%d", &n);
    frac res,cur;
    res.up=0;
    res.down=1;
    for(int i = 0;i < n; i++){
        scanf("%lld/%lld", &cur.up, &cur.down);
        res = add(res, cur);
    }
    if(res.down == 1){
        printf("%lld\n",res.up);
    }else{
        if(res.up > res.down){
            printf("%lld %lld/%lld\n",res.up / res.down, res.up % res.down, res.down);
        }else{
            printf("%lld/%lld\n", res.up, res.down);
        }
    }
    return 0;
}
相关推荐
MediaTea1 天前
AI 术语通俗词典:C4.5 算法
人工智能·算法
Navigator_Z1 天前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
WBluuue1 天前
数据结构与算法:莫队(一):普通莫队与带修莫队
c++·算法
风筝在晴天搁浅1 天前
n个六面的骰子,扔一次之后和为k的概率是多少?
算法
MATLAB代码顾问1 天前
Python实现蜂群算法优化TSP问题
开发语言·python·算法
代码飞天1 天前
机器学习算法和函数整理——助力快速查阅
人工智能·算法·机器学习
jiushiapwojdap1 天前
LU分解法求解线性方程组Matlab实现
数据结构·其他·算法·matlab
笨笨饿1 天前
69_如何给自己手搓一个串口
linux·c语言·网络·单片机·嵌入式硬件·算法·个人开发
纽扣6671 天前
【算法进阶之路】链表进阶:删除、合并、回文与排序全解析
数据结构·算法·链表
消失的旧时光-19431 天前
统一并发模型:线程、Reactor、协程本质是一件事(从线程到协程 · 第6篇·终章)
java·python·算法