pata1081(应该是long long类型却写成int类型也会超时)

本文介绍了一个算法问题:给定一系列分数形式的有理数,如何计算它们的总和并简化结果。文章通过示例展示了输入输出格式,并提供了一段C++代码实现,该算法能够处理最多100个有理数的加法运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1081. Rational Sum (20)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

Given N rational numbers in the form "numerator/denominator", you are supposed to calculate their sum.

Input Specification:

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.

Output Specification:

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.

Sample Input 1:
5
2/5 4/15 1/30 -2/60 8/3
Sample Output 1:
3 1/3
Sample Input 2:
2
4/3 2/3
Sample Output 2:
2
#include<iostream> 
#include<vector>
#include<string>
using namespace std;  
typedef long long ll; 
ll getGCD(ll a,ll b){  
    ll temp;  
    if(a < b){  
      temp = a;  
      a = b;  
      b = temp;  
    }    
    if(a%b == 0){  
        return b;    
    }else{    
        return getGCD(b,a%b);    
    }    
}
ll doLCM(vector<ll> array,ll size){    
    ll x,y,num=array[0],i,gcd;    
    for(i=0;(i+1)<size;i++){  
        x=num;    
        y=array[i+1];    
        gcd = getGCD(x,y);      
    	num = x/gcd * y/gcd * gcd;  
    }  
    return num;    
}   

int main()
{
	ll n;
	cin>>n;
	vector<ll> va,vb;
	vector<char> vc;
	for(ll i=0;i<n;i++){
		ll a=0,b=0;
		char c;
		cin>>a>>c>>b;
		va.push_back(a);
		vb.push_back(b);
		vc.push_back(c);
	}
	ll tt=0;
	tt=doLCM(vb,vb.size());
	ll ans=0;
	for(ll i=0;i<va.size();i++){
		ans+=(va[i]*(tt/vb[i]));
	}
	if(ans==0){
		cout<<0<<endl;
	}else{
		ll k=0;
		k=getGCD(ans,tt);
		tt/=k;
		ans/=k;
		ll integer=ans/tt;
		ans-=(tt*integer);
		if(integer==0){
			if(ans!=0)
			cout<<ans<<'/'<<tt<<endl;
			else{
				cout<<0<<endl;
			}
		}else{
			if(ans!=0)
			cout<<integer<<' '<<ans<<'/'<<tt<<endl;
			else{
				cout<<integer<<endl;
			}
		}
	}
	 return 0;
}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值