• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
村雨sup
自己选的路,跪着也要走完 XD
博客园    首页    新随笔    联系   管理    订阅  订阅
PAT 1081 Rational Sum
1081 Rational Sum (20 分)
 

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 (≤), 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

Sample Input 3:

3
1/3 -1/6 1/8

Sample Output 3:

7/24


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;


//  a/a1 + b/b1


ll to_int(string s){
    ll sum = 0; bool flag = 1;
    if(s[0] == '-'){
        flag = 0;
        s = s.substr(1,s.size()-1);
    }
    for(int i=0;i < s.size();i++){
        sum = sum*10 + (s[i]-'0');
    }
    if(flag) return sum;
    else return -sum;
}

ll gcd(ll x,ll y){
    return y?gcd(y,x%y):x;
}




//  a/a1 + b/b1

int main(){
    int t;cin >> t;
    ll a = 0,a1 = 1;

    while(t--){
        string s; cin >> s;
        int pos = s.find('/');
        string stra = s.substr(0,pos);
        string stra1 = s.substr(pos+1,s.size()-pos);
        ll b = to_int(stra);
        ll b1 = to_int(stra1);

        ll c = a*b1 + b*a1;
        ll c1 = a1*b1;

        ll t = gcd(c,c1);

        a = c/t;
        a1 = c1/t;
    }

    ll x = a/a1;
    ll y = a%a1;

    if(x&&y){printf("%lld %lld/%lld",x,y,a1);}
    else if(!x&&y){printf("%lld/%lld",y,a1);}
    else if(x&&!y)printf("%lld",x);
    else printf("0");

    return 0;
}

——一开始把输出写错了。。

posted on 2019-04-27 22:22  村雨sup  阅读(104)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3