L1-009 N個數求和

Frodnx發表於2024-07-31

不開long long見祖宗

// 15'22"
#include <iostream>
using namespace std;
#define int long long
class fru
{
public:
    int fz;
    int fm;
    fru(int x = 0, int y = 1):fz(x),fm(y){}
};
int gcd(int a, int b)
{
	return b ? gcd(b, a % b) : a;
}
int lcm(int a, int b)
{
	return (a * b) / gcd(a, b);
}
fru add(fru a, fru b)
{
	int l = lcm(a.fm, b.fm);
	int newfz = a.fz * (l / a.fm) + b.fz * (l / b.fm);
	int newfm = l;
	fru res(newfz,newfm);
	return res;
}
void huajian(fru a)
{
	int g = gcd(a.fz,a.fm);
	a.fz /= g;
	a.fm /= g;
	int fint = a.fz / a.fm;
	int fdou = a.fz % a.fm;
	if(fint == 0 && fdou == 0)
	{
		cout << 0;
		return;
	}
	if(fint != 0) cout << fint;
	if(fint != 0 && fdou != 0) cout << " ";
	if(fdou != 0)
	{
		cout << fdou << "/" << a.fm;
	}
}

signed main()
{
    int n;
    cin >> n;
    fru res;
    for(int i = 1; i <= n; ++ i)
    {
        int a, b;
        char c;
        cin >> a >> c >> b;
        fru f(a,b);
        res = add(res,f);
    }
    huajian(res);
    return 0;
}

相關文章