Result: Accepted
Time: 5ms
Memory: 1712kB
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
ll gcd(ll a, ll b)
{
if (b == 0)
{
return a;
}
else
{
return gcd(b, a%b);
}
}
int main()
{
int nn;
ll a[1010], b[1010];
char zz;
cin >> nn;
for (int i = 0; i < nn; i++)
{
cin >> a[i] >> zz >> b[i];
}
ll s1 = b[0];
for (int i = 1; i < nn; i++)
{
s1 = s1 / gcd(s1, b[i])*b[i];
}
ll s2 = 0;
for (int i = 0; i < nn; i++)
{
s2 += s1 / b[i] * a[i];
}
ll m = s2 / s1;
ll n = s2 % s1;
ll t = gcd(fabs(n), fabs(s1));
n = n / t;
s1 = s1 / t;
if (m < 0 && n < 0)
{
n = -n;
}
if (n == 0)
{
cout << m;
}
else if (m == 0 && n != 0)
{
cout << n << "/" << s1;
}
else
{
cout << m << " " << n << "/" << s1;
}
return 0;
}