741u741   2년 전

문제를 python, cpp, java, js 로 풀고있습니다.

그런데, python, cpp, java 로 풀이한 코드와 같은 로직을 구현했다고 생각하는데, 어디서 잘못된 건지 도통 모르겠습니다. 

정답으로 채점받았던 cpp 코드입니다.

#include
#include
using namespace std;

vector arr;
vector tree;
vector lazy;

long long I(int s, int e, int tree_idx) {
  if (s == e) {
    tree[tree_idx] = arr[s];
    return arr[s];
}

  int mid = (s + e) / 2;
  tree[tree_idx] = I(s, mid, tree_idx * 2) + I(mid + 1, e, tree_idx * 2 + 1);
  return tree[tree_idx];
}

void UU(int s, int e, int tree_idx) {
  if (lazy[tree_idx]) {
    tree[tree_idx] += (e - s + 1) * lazy[tree_idx];
    if (s != e) {
      lazy[tree_idx * 2] += lazy[tree_idx];
      lazy[tree_idx * 2 + 1] += lazy[tree_idx];
    }
  lazy[tree_idx] = 0;
  }
}

long long S(int s, int e, int l, int r, int tree_idx) {
  UU(s, e, tree_idx);

  if (s > r || e < l) {
    return 0;
  }

  if (l <= s && r >= e) {
    return tree[tree_idx];
  }

  int mid = (s + e) / 2;
  return S(s, mid, l, r, tree_idx * 2) + S(mid + 1, e, l, r, tree_idx * 2 + 1);
}

void U(int s, int e, int l, int r, int tree_idx, long long c) {
  UU(s, e, tree_idx);

  if (s > r || e < l) {
    return;
  }

  if (s >= l && e <= r) {
    tree[tree_idx] += (e - s + 1) * c;
      if (s != e) {
        lazy[tree_idx * 2] += c;
        lazy[tree_idx * 2 + 1] += c;
      }
    return;
  }

  int mid = (s + e) / 2;
  U(s, mid, l, r, tree_idx * 2, c);
  U(mid + 1, e, l, r, tree_idx * 2 + 1, c);
  tree[tree_idx] = tree[tree_idx * 2] + tree[tree_idx * 2 + 1];
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);

  int N, M, K;
  cin >> N >> M >> K;

  arr.resize(N + 1);
  tree.resize(4 * N + 1);
  lazy.resize(4 * N + 1);

  for (int i = 1; i <= N; ++i) {
    cin >> arr[i];
  }

  I(1, N, 1);

  for (int i = 0; i < M + K; ++i) {
    int a;
    cin >> a;
    if (a == 1) {
      int b, c;
      long long d;
      cin >> b >> c >> d;
      U(1, N, b, c, 1, d);
    }

    else {
      int b, c;
      cin >> b >> c;
      cout << S(1, N, b, c, 1) << '\n';
    }
  }

  return 0;
}

위 cpp 코드와 같은 로직을 js로 구현헀는데, 어디가 잘못된 건지 모르곘습니다...

741u741   2년 전

숫자 범위가 문제였습니다. js에도 처리할 수 있는 정수 범위가 있었네요...

BigInt라는 것을 배워갑니다...

댓글을 작성하려면 로그인해야 합니다.