sibindon's blog

By sibindon, history, 6 weeks ago, In English,

I don't understand why my code is giving TLE. Not able to catch the bug. Any help would be appreciated !!! Link to Question

#include<bits/stdc++.h>
# define    all(a)              a.begin(), a.end()
#define MOD (long long int )1e9+7
using namespace std;

typedef long long int ll;

ll dp[110][100010];
ll solve(int index, ll currweight, ll weight, vector<vector<int>> nums, int n) {
    if (index == n)
        return 0;
    if (dp[index][currweight] != -1)
        return dp[index][currweight];
    ll res = solve(index+1, currweight, weight, nums, n);
    if (currweight+nums[index][0] <= weight) {
        res = max(res, nums[index][1] + solve(index+1, currweight+nums[index][0], weight, nums, n));
    }
    dp[index][currweight] = res;
    return res;
}


int main() {
    #ifndef ONLINE_JUDGE
    // for getting input from input.txt
    freopen("input.txt", "r", stdin);
    // for writing output to output.txt
    freopen("output.txt", "w", stdout);
    #endif
    int n, k;
    cin >> n >> k;
    vector<vector<int>> nums(n, vector<int>(2));
    for (int i=0; i<n; i++) cin >> nums[i][0] >> nums[i][1];
    memset(dp, -1, sizeof(dp));
    ll res = solve(0, 0, k, nums, n); 
    cout << res << endl;
    return 0;
}
 
 
 
 
  • Vote: I like it
  • -9
  • Vote: I do not like it

»
6 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

I don't know which problem you are referring to, but I see that you are passing the parameter vector<vector<int>> nums by value instead of by reference in your solve function. This means that every time you make a call to that function, the whole structure is copied, value by value. To solve this, just put an & after the type, like this: vector<vector<int>>& nums, and see if that gets AC.

Here's a webpage that talks about passing by reference, in case you want to know more about it. It's really important.

  • »
    »
    6 weeks ago, # ^ |
      Vote: I like it -9 Vote: I do not like it

    Didn't know pass by value would cost this much. Thank you!! Got AC

»
6 weeks ago, # |
  Vote: I like it +3 Vote: I do not like it

Can you pls upload a link to the problem?

»
6 weeks ago, # |
  Vote: I like it -6 Vote: I do not like it

Auto comment: topic has been updated by sibindon (previous revision, new revision, compare).