L1-009. N个数求和

L1-009. N个数求和

题目链接:https://www.patest.cn/contests/gplt/L1-009

本题乍一看挺简单的,实际上却有很多坑,debug用去了不少时间。

代码如下:

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<cmath>
 4 #define LL long long
 5 using namespace std;
 6 LL a[101],b[101];
 7 LL gcd(LL x,LL y){
 8     return y==0?x:gcd(y,x%y);
 9 }
10 void simple(LL i){
11     LL temp=gcd(abs(a[i]),b[i]);
12     a[i]/=temp;
13     b[i]/=temp;
14 }
15 int main(void){
16     //freopen("1.in.txt","r",stdin);
17     LL n;
18     scanf("%lld",&n);
19     for(LL i=0;i<n;++i){
20         scanf("%lld/%lld",&a[i],&b[i]);
21         simple(i);
22     }
23     long long x=a[0],y=b[0];
24     for(LL i=1;i<n;i++){
25         x=x*b[i]+y*a[i];
26         y=y*b[i];
27         if(x){
28             LL temp=gcd(abs(x),y);
29             x/=temp;
30             y/=temp;
31         }
32     }
33     if(!x){
34         printf("0\n");
35         return 0;
36     }
37     LL temp=x/y;
38     x=x-temp*y;
39     LL t=gcd(abs(x),y);
40     x/=t;
41     y/=t;
42     if(temp){
43         printf("%lld",temp);
44         if(x)printf(" %lld/%lld",x,y);
45         printf("\n");
46     }else{
47         if(x)printf("%lld/%lld",x,y);
48         printf("\n");
49     }
50     return 0;
51 }

  如有更好的方法,希望不吝赐教!!

posted @ 2016-06-01 00:01  barriery  阅读(549)  评论(0编辑  收藏  举报