PTA天梯赛-练习集 L1-009 N个数求和

PTA天梯赛-练习集 L1-009 N个数求和
模拟通分

#include <bits/stdc++.h>
using namespace std;
#define d(x) cout << (x) << endl

typedef long long ll;
const int N = 1e2 + 10;
const int INF = 0x3f3f3f3f;

struct node{
    ll x, y;
    node(ll x, ll y):x(x),y(y){}
    node(){}
};
node arr[N];

node f(node m, node n)
{
    ll num = m.y * n.y / __gcd(m.y, n.y);
    ll num1 = m.x * (num / m.y) + n.x * (num / n.y);
    node ans = node(num1, num);
    return ans;
}

int main()
{
    int n;
    cin >> n;
    for (int i = 0; i < n; i++){
        ll a, b;
        char c;
        scanf("%lld%c%lld", &a, &c, &b);
        // printf("%d %d\n", a, b);
        arr[i] = node(a, b);
    }
    node ans = arr[0];
    for (int i = 1; i < n; i++){
        ans = f(ans, arr[i]);
        // printf("%d %d\n", ans.x, ans.y);
    }
    ll cntx = ans.x / __gcd(ans.x, ans.y);
    ll cnty = ans.y / __gcd(ans.x, ans.y);
    if(cntx < 0){
        printf("-");
        cntx = -cntx;
    }
    if(cntx == 0){
        printf("0\n");
        return 0;
    }
    if(cntx < cnty){
        printf("%lld/%lld\n", cntx, cnty);
    }else if(cntx == cnty){
        printf("1\n");
    }else{
        if(cntx % cnty == 0){
            printf("%lld\n", cntx / cnty);
        }else{
            ll num1 = cntx / cnty;
            ll num2 = cntx % cnty;
            printf("%lld %lld/%lld\n", num1, num2, cnty);
        }
    }
    return 0;
}