题目不难,但是需要注意的细节很多,尤其是 long long虽然数的范围在int内,但是求最小公倍数时,相乘会超出int范围,因此用long long;
AC代码:
#include<iostream>
#include<map>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cstring>
#include<list>
#include<set>
#include<stack>
#include<cmath>
#include<vector>
#define inf 999999999
using namespace std;
long long gcd(long long x,long long y)
{
return x%y==0?y:gcd(y,x%y);
}
long long f(long x,long y)
{
return x*y/gcd(x,y);
}
int main()
{
long long n;
scanf("%d",&n);
long long fenzi=0;
long long fenmu=1;
//cout<<fenzi<<" "<<fenmu<<endl;
for(int i=0;i<n;i++)
{
string s;
cin>>s;
long long tmp1=0;
long long tmp2=0;
int flag1=0;
if(s[0]=='-')
{
flag1=1;
s.erase(0,1);
}
int j;
for(j=0;j<s.size();j++)
{
if(s[j]=='/')
break;
tmp1*=10;
tmp1+=s[j]-'0';
}
tmp1=flag1==1?-tmp1:tmp1;
for(int r=j+1;r<s.size();r++)
{
tmp2*=10;
tmp2+=s[r]-'0';
}
long long gg=f(fenmu,tmp2);
//cout<<gg<<endl;
fenzi=fenzi*gg/fenmu;
tmp1=tmp1*gg/tmp2;
fenmu=gg;
fenzi=fenzi+tmp1;
if(fenzi==0)
{
fenmu=1;
continue;
}
long long fac=gcd(fenmu,fenzi);
//cout<<fac<<endl;
fenmu=fenmu/fac;
fenzi=fenzi/fac;
//cout<<fenzi<<" "<<fenmu<<endl;
}
if(fenmu==1)
{
if(fenzi<0)
{
printf("-%lld",-fenzi);
}
else
{
printf("%lld",fenzi);
}
}
else
{
if(fenzi/fenmu==0)
{
printf("%lld/%lld",fenzi,fenmu);
}
else
{
int d=fenzi/fenmu;
printf("%lld %lld/%lld",d,fenzi-d*fenmu,fenmu);
}
}
}