转自:http://blog.csdn.net/dengkuomin/article/details/61198397
题目链接:https://www.patest.cn/contests/gplt/L1-009
解题思路:先求出所有分数的最小公分母,注意处理数据,不能超长整形,然后求分子,最后判断整数部分和分数部分。
代码如下:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define LL long long
using namespace std;
LL gcd(LL a,LL b)///求最大公约数
{
return a%b==0?b:gcd(b,a%b);
}
int main()
{
LL t,a[101],b[101],s1=0,s2=0;
scanf("%lld",&t);
for(int i=0; i<t; i++)
scanf("%lld/%lld",&a[i],&b[i]);
s2=b[0];
for(int i=1; i<t; i++)
s2=s2/gcd(s2,b[i])*b[i];///求出所有分数的公分母
for(int i=0; i<t; i++)
s1+=s2/b[i]*a[i];///求分子总和
LL n=s1/s2,m=abs(s1%s2);
if(m==0) printf("%lld\n",n);
else
{
if(n!=0)printf("%lld ",n);
if(s1<0&&n==0)printf("-");
printf("%lld/%lld\n",m/gcd(s2,m),s2/gcd(s2,m));
}
return 0;
}