sharpcoder's blog

By sharpcoder, history, 9 years ago, In English

Following are two codes of same problem SPOJ MIXTURES. The first is getting accepted but the second one is showing time limit exceeded. Although, Both codes are completely same. but the only difference between following codes is in line no. 12 (numbered) i.e int &r in first code and only int r in second. Please tell why the second code getting time limit exceeded and first one is getting accepted.

FIRST CODE

 #include <bits/stdc++.h>

using namespace std;

int a[100],sum[100][100],dp[100][100];
int solve(int ai,int bi){
    if(ai==bi){
       return 0;
    }
    if((ai+1)==bi)
        return a[ai] * a[bi];
12.         **int &r= dp[ai][bi],c;**
        if(r==-1){
            for(int i=ai;i+1<=bi;i++){
                c= sum[ai][i] * sum[i+1][bi] + solve(ai,i) + solve(i+1,bi);
            if(r==-1 || c<r)r=c;
            }
        }
        return r;
}
int main()
{
    int n;
    while(scanf("%d", &n)==1){
        for(int i=0;i<n;i++)
             scanf("%d",&a[i]);
            for(int i = 0;i < n;++i) sum[i][i] = a[i];
            for(int i=0;i<n;i++){
                for(int j=i+1;j<n;j++){
                    sum[i][j]=sum[i][j-1] + a[j];
                    if(sum[i][j]>=100)
                        sum[i][j]-=100;
                }

            }
            memset(dp,-1,sizeof dp);
             printf("%d\n",solve(0,n-1));


    }

    return 0;
}

SECOND CODE

#include <bits/stdc++.h>

using namespace std;

int a[100],sum[100][100],dp[100][100];
int solve(int ai,int bi){
    if(ai==bi){
       return 0;
    }
    if((ai+1)==bi)
        return a[ai] * a[bi];
12.         **int r= dp[ai][bi],c;**
        if(r==-1){
            for(int i=ai;i+1<=bi;i++){
                c= sum[ai][i] * sum[i+1][bi] + solve(ai,i) + solve(i+1,bi);
            if(r==-1 || c<r)r=c;
            }
        }
        return r;
}
int main()
{
    int n;
    while(scanf("%d", &n)==1){
        for(int i=0;i<n;i++)
             scanf("%d",&a[i]);
            for(int i = 0;i < n;++i) sum[i][i] = a[i];
            for(int i=0;i<n;i++){
                for(int j=i+1;j<n;j++){
                    sum[i][j]=sum[i][j-1] + a[j];
                    if(sum[i][j]>=100)
                        sum[i][j]-=100;
                }

            }
            memset(dp,-1,sizeof dp);
             printf("%d\n",solve(0,n-1));


    }

    return 0;
}

Tags dp, c++, spoj
  • Vote: I like it
  • 0
  • Vote: I do not like it

| Write comment?
»
9 years ago, # |
Rev. 47   Vote: I like it +1 Vote: I do not like it

There is no memoization in the second code because you are creating variable r, changing its value, but not changing dp[ai][bi]

In the first code r is a reference to dp[ai][bi], so changing r will change dp[ai][bi]