Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×
Изменения рейтингов за последние раунды временно удалены. Скоро они будут возвращены. ×

Блог пользователя TanvirZihad

Автор TanvirZihad, история, 12 месяцев назад, По-английски
Bismillahir Rahmanir Rahim

While solving the CSES-BOOK Shop problem, I used TOP DOWN approach having complexity O(n.m) approach at first. But it gives TLE. But when I used bottom up approach, it got accepted. Why my Top Down approach got TLE ?I am confused.

TOP DOWN approach

#include<bits/stdc++.h>
#include<iostream>
#define ff first
#define ss second 
#define pb push_back
#define ll long long
#define noob ios::sync_with_stdio(0);cin.tie(0);
using namespace std;
int n;
int a[1005],b[1005],dp[1005][100005];
int solve(int i,int m){
	if(i==n){
		return 0;
	}
	if(dp[i][m]!=-1)return dp[i][m];
	int ans=0;
	ans=max(ans,solve(i+1,m));
	if(m>=a[i]){
		ans=max(ans,solve(i+1,m-a[i])+b[i]);
	}
	return dp[i][m]= ans;
}
int main(){
	int m;
	cin>>n>>m;
	memset(dp,-1,sizeof(dp));
	for(int i=0;i<n;i++)cin>>a[i];
	for(int j=0;j<n;j++)cin>>b[j];
	cout<<solve(0,m)<<endl;
	return 0;
	
    
}

BOTTOM UP approach

#include<bits/stdc++.h>
#include<iostream>
#define ff first
#define ss second 
#define pb push_back
#define ll long long
#define noob ios::sync_with_stdio(0);cin.tie(0);
using namespace std ;
int main(){
    int n,m;
    cin>>n>>m;
    vector<int>a(n),b(n);
    for(int i=0;i<n;i++)cin>>a[i];
    for(int j=0;j<n;j++)cin>>b[j];
    int dp[n+1][m+1];
    memset(dp,0,sizeof(dp));
    for(int i=1;i<=n;i++){
        for(int j=0;j<=m;j++){
            dp[i][j]=dp[i-1][j];
            if(j>=a[i-1]){
                dp[i][j]=max(dp[i][j],dp[i-1][j-a[i-1]]+b[i-1]);
            }
        }
    }
    cout<<dp[n][m]<<endl;
}
  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
12 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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

»
12 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

First of all, CSES has very very strict time limits and it happens often that solutions which have the right complexity get TLE because of inefficient code. Generally, recursive programs have large overhead and run much slower than iterative ones. Perhaps if the same problem was on codeforces, both solutions would pass, but on CSES, most recursive solutions will get TLE (at least for this problem).

»
12 месяцев назад, # |
Rev. 2   Проголосовать: нравится +1 Проголосовать: не нравится

1) use arrays

2) don't use bits

3) write noob in the main function to speedup the code

AC CODE:https://cses.fi/paste/7c9e1dfef6715b96701c1e/ (your code with my changes)