PrasoonJha's blog

By PrasoonJha, history, 18 months ago, In English

I am using knuth's optimization for solving this problem Spoj Breaking String with given code

int n,m;
        cin>>n>>m;
        vector<int> v(m+2);
        for(int i=1;i<m+1;i++)    cin>>v[i];
        v[m+1] = n;
        sort(v.begin(),v.end());
        vector<vector<int>> dp(m+2,vector<int>(m+2,1e9));
        vector<vector<int>> opt(m+2,vector<int>(m+2,1e4));

        for(int i=0;i<m+2;i++)
        {
            dp[i][i] = 0;
            opt[i][i] = i;
        }

        for(int i = m;i>=0;i--)
        {
            for(int j=i+1;j<m+2;j++)
            {
                int ans = 1e9;
                for(int k = opt[i][j-1];k<=min(j-1,opt[i+1][j]);k++)
                {
                    //cout<<dp[i][k]+dp[k][j]+(v[j]-v[i])<<"\n";
                    if(ans>=(dp[i][k]+dp[k][j]+(v[j]-v[i])))
                    {
                        ans = (dp[i][k]+dp[k][j]+(v[j]-v[i]));
                        opt[i][j] = k;
                    }
                }
                if(ans!=1e9)    dp[i][j] = ans;
                else
                {
                    dp[i][j] = 0;
                    opt[i][j] = i;
                }
            }
        }
        cout<<dp[0][m+1]<<"\n";

I have already defined int as long long.

It is giving WA I have tried everything but unable to find issue please tell me if I am doing something wrong here.

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

By PrasoonJha, history, 3 years ago, In English

When i was submitting my solution in leetcode, I was getting TLE when passing string by value but after changing it to string by reference it got faster. I thought strings were passes by refence automatically anyways. Below are images of code being accepted and not accepted.

Full text and comments »

  • Vote: I like it
  • -12
  • Vote: I do not like it