Some problems in CSES problem set take more time then it should

Revision en1, by salt_n_ice, 2020-10-30 06:55:43

This is the problem I am talking about, although this has happened with some other problems as well. The solution is straightforward using dp, but I was getting TLE for 2 test cases, and the time complexity was O(n*x) so I thought some optimization was required, so I then looked at his stream and he did exactly the same as me, Only minor differences, which I changed in my solution to make it look exactly like him. But Still! It's still showing TLE while his was accepted! Here is the solution:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll N =1e9+7;
int main()
{
    int n, x;
    cin>>n>>x;
    int a[n];
    for(int i=0; i<n; ++i)
    {
        cin>>a[i];
    }
    ll cnt[x+1]={0};
    cnt[0]=1;
    for(ll i=1; i<=x; ++i)
    {
        for(ll j = 0; j<n; ++j)
        {
            if(i>=a[j])
            cnt[i] = (cnt[i]+cnt[i-a[j]])%N;
        }
    }
    cout<<cnt[x];
}

Tags #dp, #cses, #complexity

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English salt_n_ice 2020-10-30 06:55:43 1105 Initial revision (published)