My apologies, I know this type of question already has an answer over here but I couldn't figure out how to use it for my code. I wrote a program for a problem-solving contest that accepts an array and tries to maximize the value of |Ax−Ay|+|Ay−Az|+|Az−Ax| over all triples of pairwise distinct valid indices (x,y,z). The program has the following constraints:
I am getting the following error when I try to run it - "terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc". All I could figure out from the answered questions was that my code encounters memory allocation problem but I couldn't find where and when it does that? Maybe when it deals with large values? What is causing the error?
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef vector<ll> vll;
typedef vector<int> vi;
#define rep(i, a, b) for (ll i = a; i < b; i++)
#define repi(i, a, b) for (ll i = a; i <= b; i++)
#define repn(i, a, b) for (ll i = a; i >= b; i--)
#define fast() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL)
#define all(x) (x).begin(), (x).end()
// solve() function
void solve()
{
ll n;
cin >> n;
vll v(n);
rep(i, 0, n)
cin >>
v[i];
sort(all(v));
ll x = v[0], y = v[1], z = v[n - 1];
ll ans = abs(x - y) + abs(y - z) + abs(z - x);
cout << ans << endl;
}
// driver function
int main()
{
fast();
ll t = 1;
cin >> t;
rep(i, 0, t)
{
solve();
}
return 0;
}
The input format is as follows:
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers A1, A2,…,AN.
The following is a sample input:
3
3
2 7 5
3
3 3 3
5
2 2 2 2 5
you have to do something like this: I am not getting data via cin
I am just specifying the value.
void solve()
{
ll n =100000000;
vll v;
v.reserve(n);
//omitted
}
it runs fine,and it does not throw bad_alloc
error. In your case, n
may be uninitialized, and is not getting valid input so it pass n that is very big. when vll v(n)
try to allocate it runs out of memory and returns 137
which means out of memory. so it fails. If you specify n
directly into the constructor of vector
it will allocate more memory(compiler dependent). But if you reserve the memory you need, it works fine until you have enough memory to hold the data you are putting in the vector
.