-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1081.cpp
76 lines (65 loc) · 1.08 KB
/
1081.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
struct Fraction
{
ll up;
ll down;
};
Fraction f[100];
Fraction add(const Fraction &f1, const Fraction &f2);
ll gcd(ll a, ll b);
int main()
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%lld/%lld", &f[i].up, &f[i].down);
}
Fraction ans;
ans.up = 0;
ans.down = 1;
int d;
for (int i = 0; i < n; i++)
{
ans = add(ans, f[i]);
if (ans.up == 0)
{
ans.down = 1;
}
else
{
// 计算最大公约数进行约分
d = gcd(abs(ans.down), abs(ans.up));
ans.up /= d;
ans.down /= d;
}
}
if (ans.down == 1) //整数
{
printf("%lld", ans.up);
}
else if (ans.up > ans.down) //假分数
{
printf("%lld %lld/%lld", ans.up / ans.down, abs(ans.up%ans.down), ans.down);
}
else // 真分数
{
printf("%lld/%lld", ans.up, ans.down);
}
return 0;
}
Fraction add(const Fraction &f1, const Fraction &f2)
{
Fraction ans;
ans.down = f1.down*f2.down;
ans.up = f1.up*f2.down + f1.down*f2.up;
return ans;
}
ll gcd(ll a, ll b)
{
if (b == 0)return a;
gcd(b, a%b);
}