1081 Rational Sum (20 分)【难度: 一般/ 知识点: 模拟】

在这里插入图片描述
https://pintia.cn/problem-sets/994805342720868352/problems/994805386161274880

#include<bits/stdc++.h>
using namespace std;
typedef long long int LL;
LL n,a,b,s1,s2,cnt;
LL gcd(LL a,LL b) {
    
    return b?gcd(b,a%b):a;}
void solve(LL a,LL b)
{
    
    
    LL temp1=gcd(labs(a),labs(b));
    a/=temp1,b/=temp1;//通分
    LL temp=s2/gcd(s2,b)*b;
    s1=s1*(temp/s2),a=a*(temp/b);
    s1=s1+a,s2=temp;
    cnt+=s1/s2;
    s1=s1%s2;
    temp=gcd(labs(s1),labs(s2));
    s1/=temp,s2/=temp;
}
int main(void)
{
    
    
    cin>>n;
    scanf("%lld/%lld",&s1,&s2);
    for(int i=2;i<=n;i++) scanf("%lld/%lld",&a,&b),solve(a,b);
    if(cnt&&!s1) printf("%lld",cnt);//只有整数
    else if(cnt&&s1) printf("%lld %lld/%lld",cnt,s1,s2);//有整有分
    else if(s1) printf("%lld/%lld",s1,s2);//只有分数
    else printf("0");//0
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_46527915/article/details/121184710