Result: Accepted
Time: 7ms
Memory: 1712kB
#include<iostream>
#include<istream>
#include<cmath>
using namespace std;
int gcd(int a,int b)
{
return a%b==0 ? b : gcd(b,a%b);
}
int fcm(int a,int b)
{
return a*b/gcd(a,b);
}
struct fraction
{
int flag;
int a,b;
};
struct fraction flex (struct fraction f,int x)
{
struct fraction temp;
temp.a=f.a*x/f.b;
temp.b=x;
temp.flag=f.flag;
//cout << temp.a <<" " << temp.b<<endl;
return temp;
}
void fplus (struct fraction* f1,struct fraction* f2)
{
int x=fcm(f1->b,f2->b);
*f1=flex(*f1,x);
*f2=flex(*f2,x);
f1->a=f1->a*f1->flag+f2->a*f2->flag;
if (f1->a>0)
f1->flag=1;
else
f1->flag=-1;
f1->a=abs(f1->a);
int a=gcd(f1->a,f1->b);
f1->a/=a;
f1->b/=a;
}
int main()
{
int k,temp1,temp2,n=0,flag=0;
char c;
struct fraction f[100],ans;
cin >> k ;
while (k--)
{
cin >> temp1;
cin >> c;
cin >> temp2;
if (temp1<0)
f[n].flag=-1;
else
f[n].flag=1;
f[n].a=abs(temp1);
f[n].b=temp2;
n++;
}
ans=f[0];
for (int i=1;i<n;i++)
{
fplus(&ans,&f[i]);
}
//cout << ans.flag <<" " <<ans.a <<" "<< ans.b <<endl;
if (ans.a==0)
{
cout << "0" << endl;
return 0;
}
if (ans.flag<0)
{
cout << "-";
}
int integer=ans.a/ans.b;
ans.a-=integer*ans.b;
if (integer!=0)
{
cout << integer;
flag=1;
}
if (ans.a!=0)
{
if (flag)
cout <<" ";
cout << ans.a << "/" << ans.b<<endl;
}
}