Result: Accepted
Time: 4ms
Memory: 1092kB
#include<stdio.h>
#include<string.h>
int gcd(int x, int y) {
if (y == 0) return x;
gcd(y, x%y);
}
int main() {
int n;
int a, b,x;
char c;
int zh = 0;
int ans1, ans2;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d%c%d", &a, &c, &b);
if (i == 1) {
if(a>0) x = gcd(a, b);
else if(a<0) x = gcd(-1*a, b);
ans1 = a / x;
ans2 = b / x;
zh += ans1 / ans2, ans1 -= ans2 * (ans1 / ans2);
}
else {
ans1 = ans1 * b + ans2 * a;
ans2 = ans2 * b;
if(ans1>0) x = gcd(ans1, ans2);
else if(ans1<0) x = gcd(-1*ans1, ans2);
ans1 /= x;
ans2 /= x;
zh += ans1 / ans2, ans1 -= ans2 * (ans1 / ans2);
}
}
if(zh!=0&&ans1!=0){
if(zh>0) printf("%d %d/%d\n", zh, ans1, ans2);
else printf("%d %d/%d\n", zh, -1*ans1, ans2);
}
else if(ans1==0) printf("%d\n",zh);
else printf("%d/%d\n",ans1, ans2);
}