L1-009. N个数求和

落爺英雄遲暮 提交于 2019-12-17 13:02:45

本题的要求很简单,就是求N个数字的和。麻烦的是,这些数字是以有理数“分子/分母”的形式给出的,你输出的和也必须是有理数的形式。

输入格式:

输入第一行给出一个正整数N(<=100)。随后一行按格式“a1/b1 a2/b2 ...”给出N个有理数。题目保证所有分子和分母都在长整型范围内。另外,负数的符号一定出现在分子前面。

输出格式:

输出上述数字和的最简形式 —— 即将结果写成“整数部分 分数部分”,其中分数部分写成“分子/分母”,要求分子小于分母,且它们没有公因子。如果结果的整数部分为0,则只输出分数部分。

输入样例1:

5
2/5 4/15 1/30 -2/60 8/3

输出样例1:

3 1/3
很简单的题,就是写起来麻烦一点,算是练基础功了
#include <iostream>
#include <cstring>
#include <algorithm> 
#include <stdio.h>
#include <stdlib.h>
#define ll long long
using namespace std;
string s[105];
struct node{
 ll fz,fm;
 int f=1;
}num[105];
void out(node ans)
{
 cout<<ans.f<<" "<<ans.fz<<" "<<ans.fm<<endl;
}
node read(string x)
{
 node ans;
 int l=x.length(),start=0,k;
 ll nz,nm;
 string z,m;
 char cz[100],cm[100];
 if(x[0]=='-') ans.f=-1,start+=1;
 for(int i=start;i<l;i++) if(x[i]=='/') k=i;
 for(int i=start;i<=k-1;i++) z+=x[i];
 strcpy(cz, z.c_str());
 nz=strtol(cz,NULL,10);
 
 m=x.substr(k+1,l-1);
 strcpy(cm,m.c_str());
 nm=strtol(cm,NULL,10);
 
 ans.fz=nz,ans.fm=nm;
 if(nz==0||nm==0) ans.f=-2;
 return ans;
}
node add(node x,node y)
{
 if(x.f==-2&&y.f!=-2) return y;
 if(x.f!=-2&&y.f==-2) return x;
 node ans;
 if(x.f*y.f==1)
 {
  ans.fm=x.fm*y.fm;
  ans.fz=x.fz*y.fm+x.fm*y.fz;
  ans.f=x.f;
 }
 else if(x.f==1&&y.f==-1)
 {
  ans.fm=x.fm*y.fm;
  int t=x.fz*y.fm-x.fm*y.fz;
  ans.fz=abs(t);
  if(t>0) ans.f=1;
  else if(t<0) ans.f=-1;
  else ans.f=-2;
 }
 else if(x.f==-1&&y.f==1)
 {
  ans.fm=x.fm*y.fm;
  int t=x.fm*y.fz-x.fz*y.fm;
  ans.fz=abs(t);
  if(t>0) ans.f=1;
  else if(t<0) ans.f=-1;
  else ans.f=-2;
 }
 
// out(x);
// out(y);
// out(ans);
 return ans;
}
ll gcd(ll a, ll b)
{
    ll t;
    if (a < b)
    {
        t = a;
        a = b;
        b = t;
    }    
    while (b != 0)
    {
        t = a % b;
        a = b;
        b = t;
    }
    return a;
}
node huajian(node x,ll g)
{
 node ans;
 ans.fz=x.fz/g;
 ans.fm=x.fm/g;
 ans.f=x.f;
 return ans;
}
int main()
{
 //freopen("in.txt","r",stdin);
 int n;
 cin>>n;
 for(int i=0;i<n;i++)
 {
  cin>>s[i];
  num[i]=read(s[i]);
 }
 node ans=num[0],tmp;
 for(int i=1;i<n;i++)
 {
  tmp=add(num[i],ans);//out(tmp);
  ll g=gcd(tmp.fm,tmp.fz);
  if(g!=1) ans=huajian(tmp,g);
  else ans=tmp;
  //out(ans);
 }
 if(ans.f==-1) cout<<"-";
// out(ans);
 if(ans.f==-2) cout<<0<<endl;
 else
 {
  if(ans.fz<ans.fm) cout<<ans.fz<<"/"<<ans.fm<<endl;
  else if(ans.fz==ans.fm) cout<<1<<endl;
  else 
  {
   int zheng=ans.fz/ans.fm;
   if(zheng*ans.fm==ans.fz) cout<<zheng<<endl;
   else 
   {
    cout<<zheng<<" ";
    if(ans.f==-1) cout<<"-";
    cout<<ans.fz-zheng*ans.fm<<"/"<<ans.fm<<endl;
   }
  }
 }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!