0
#include <bits/stdc++.h>
using namespace std;

int solve(int A, vector<int> &B) {
  vector<int> pre(A);
  vector<int> suff(A);
  vector<int> p;
  vector<int> s;
  int sum = 0;
  int ans = 0;

  for (int i = 0; i < A; i++) {
    sum = sum + B[i];
  }
  if (sum % 3 != 0)
    return 0;
  sum = sum / 3;

  for (int i = 0; i < A; i++) {
    if (i == 0) {
      pre[i] = B[i];
      if (pre[i] == sum) {
        p.push_back(i);
      }
      continue;
    }
    pre[i] = B[i] + pre[i - 1];
    if (pre[i] == sum) {
      p.push_back(i);
    }
  }

  for (int i = A - 1; i >= 0; i--) {
    if (i == A - 1) {
      suff[A - 1] = B[A - 1];
      if (suff[i] == sum) {
        s.push_back(i);
      }
      continue;
    }
    suff[i] = B[i] + pre[i + 1];
    if (suff[i] == sum) {
      s.push_back(i);
    }
  }
  for (int i = 0; i < p.size(); i++) {
    for (int j = s.size(); j >= 0; j++) {
      if (s[j] > p[i] + 1) {
        ans++;
      }
    }
  }
  return ans;
}

int main() {
  int A = 5;
  vector<int> B = {1, 2, 3, 0, 3};
  cout << solve(5, B);
  return 0;
}

The code keeps getting dumped at pre[i]=B[i]. The code is very simple for counting the number of ways to split all the elements of the array into 3 contiguous parts so that the sum of elements in each part is the same.

I just made a prefix and suffix sum array.

Biffen
  • 6,249
  • 6
  • 28
  • 36
  • 1
    ([Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h)) – Biffen Apr 20 '21 at 08:54
  • 2
    [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Biffen Apr 20 '21 at 08:54
  • 2
    _"core dumped"_ means a core file was created. This file contains details about the crash, the call stack, the values of the variables, ... Open it with your debugger and analyze it. It will show you where and why your program crashed. –  Apr 20 '21 at 08:55
  • 3
    Change all `arr[idx]` into `arr.at(idx)` and see where exception pops up. Ex. `int j = s.size(); j >= 0; j++) { if (s[j]` is wrong - `s[s.size()]` is out if bounds – KamilCuk Apr 20 '21 at 08:58
  • /bin/run.sh is UNIX/Linux, exe is Windows technology. Are you sure about what you are doing? – Dominique Apr 20 '21 at 09:32
  • @Dominique Executable files can be called whatever you want, *nix doesn’t care. And I think in this case the file is just `exe`. – Biffen Apr 20 '21 at 09:40

0 Answers0