时间限制 1000 ms 内存限制 65536 KB 代码长度限制 100 KB 判断程序 Standard (来自 小小)
题目描述
Given N rational numbers in the form “numerator/denominator”, you are supposed to calculate their sum.
输入描述:
Each input file contains one test case. Each case starts with a positive integer N (<=100), followed in the next line N rational numbers “a1/b1 a2/b2 …” where all the numerators and denominators are in the range of “long int”. If there is a negative number, then the sign must appear in front of the numerator.
输出描述:
For each test case, output the sum in the simplest form “integer numerator/denominator” where “integer” is the integer part of the sum, “numerator” < “denominator”, and the numerator and the denominator have no common factor. You must output only the fractional part if the integer part is 0.
输入例子:
5
2/5 4/15 1/30 -2/60 8/3
输出例子:
3 1/3
题解:
此题目涉及到分数的加减运算,先按照普通的步骤进行加减运算,然后进行约分运算,最后按照需求判断是否是假分数,这这里可以先不考虑数字的正负。
#include <bits/stdc++.h>
#include <stdlib.h>
using namespace std;
#define vi vector<int>
#define pii pair<int,int>
#define x first
#define y second
#define all(x) x.begin(),x.end()
#define pb push_back
#define mp make_pair
#define SZ(x) x.size()
#define rep(i,a,b) for(int i=a;i<b;i++)
#define per(i,a,b) for(int i=b-1;i>=a;i--)
#define pi acos(-1)
#define mod 1000000007
#define inf 1000000007
#define ll long long
#define DBG(x) cerr<<(#x)<<"="<<x<<"\n";
#define N 200010
template <class U,class T> void Max(U &x, T y){if(x<y)x=y;}
template <class U,class T> void Min(U &x, T y){if(x>y)x=y;}
template <class T> void add(int &a,T b){a=(a+b)%mod;}
int gcd(ll a,ll b){
return b==0 ? abs(a): gcd(b,a%b);
}
int main()
{
ll n,a,b,ans,sum1=0,sum2=1;
scanf("%lld",&n);
for(int i=0;i<n;i++)
{
scanf("%lld/%lld",&a,&b);
ans=gcd(a,b);
a=a/ans;
b=b/ans;
sum1=a*sum2+b*sum1;
sum2=b*sum2;
ans=gcd(sum1,sum2);
sum1=sum1/ans;
sum2=sum2/ans;
}
ll res=sum1/sum2;
sum1=sum1-(sum2*res);
if(res!=0)
{
cout<<res;
if(sum1!=0)cout<<" ";
}
if(sum1!=0)
{
printf("%lld/%lld",sum1,sum2);
}
if(res==0&&sum1==0)
printf("0");
return 0;
}