c++bad-alloc

error : terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc;


Why does my code give this bad_alloc error, even though I have allocated enough memory? I'm not able to figure it out.

this is the problem link

Passing by reference did not resolve the error.

#include <bits/stdc++.h>
using namespace std;
#define ll long long

void dfs(ll root , vector<vector<ll>> &graph , vector<ll> &weights , ll max_weight , ll &ans)
{
    for(auto adj : graph[root])
    {
        ans = max(ans , (max_weight - weights[adj]) );
        max_weight = max( max_weight , weight[adj]);
        dfs(adj , graph , weights , max_weight , ans);
    }
}

int main() {
    ll n;
    cin>>n;
    vector<ll>a(n+1 , 0);
    vector<vector<ll>>v(n+1);
    
    for(ll i=0 ;i<n;i++)
        {
            ll wt;cin>>wt;a[i]=wt;
        }
    ll root = -1;
    for(ll i=0 ;i<n;i++)
    {
        ll p;cin>>p;
        if(p == -1)root = i;
        v[p-1].push_back(i);
    }
    
    ll ans = INT_MIN;
    ll wt = a[root];
    dfs(root , v , a , wt , ans);
    cout<<ans<<endl;
    
    return 0;
}


Solution

  • dfs takes a copy of the vectors graph and a every time it is called recursively, and this probably exhausts your memory.

    Pass references instead:

      void dfs(ll root , vector<vector<ll>> const &graph , vector<ll> const &a , ll wt , ll &ans)
    

    As a side note: is there a reason you return the result in a reference parameter instead of a return value? To my mind it would be more natural to use

      ll dfs(ll root , vector<vector<ll>> const &graph , vector<ll> const &a , ll wt)
    

    and return ans from dfs.