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;
}