L1-009. N个数求和

L1-009. N个数求和

https://www.patest.cn/contests/gplt/L1-009

原来写的找了好久还是有一个测试点没过, 虽说是道水题,但是今天一遍就过了还是挺高兴的。

送你机组数据

5
2/5 4/15 1/30 -2/60 8/3
2
4/3 2/3
3
1/3 -1/6 1/8
1
-60/12
2
-1/2 1/3
1
0/1021
2
0/1 0/12
1
-1/1
1
6/6

#********************************************************************************************

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <math.h>
#define maxn 110
using namespace std;
typedef long long int ll;

ll n, a, b, sumx, sumy;

ll lcm(ll x, ll y){
if(x == y)
  return 1;
  else
  return y == 0 ? x : (lcm(y, x%y));
}

void add(ll x, ll y){

ll temp = lcm(y, sumy);
      temp = y / temp * sumy;

x *= temp / y;
      sumx *= temp / sumy;
      sumx += x;
      sumy = temp;

if(sumx < 0){
      ll te = lcm(-sumx , sumy);
      sumx /= te;
      sumy /= te;
}else{
      ll te = lcm(sumx , sumy);
      sumx /= te;
      sumy /= te;
         }
     return ;
}

int main(){

scanf("%d", &n);
sumx = 0;
sumy = 1;
for(int i=0; i<n; ++i){
     scanf("%lld/%lld", &a, &b);
     add(a, b);
}

if(sumx == 0){
   cout << "0" << endl;
}else{
  int inter = sumx / sumy;
  if(inter == 0){
  cout << sumx << "/" << sumy << endl;
}else{
  cout << inter;
  if(sumx - inter * sumy > 0){
     cout << " " << sumx - inter * sumy << "/" << sumy;
  }
  cout << endl;
}

}

return 0;
}

上一篇:7-2 堆栈操作合法性 (20 分) C++


下一篇:Synchronized 和 Lock 锁在JVM中的实现原理以及代码解析