Here you will find solutions of many problems on spoj. If you want solution of some problem which is not listed in blog or have doubt regarding any spoj problem (which i have solved) or any programming concept (data structure) you can mail me @ raj.nishant360@gmail.com

And my humble request to you all that don't copy the code only try to understand the logic and algorithm behind the code. I have started this because if you tried as hard as you can and still can't find any solution to the problem then you can refer to this.
You can read my answer how to start competitive programming CLICK HERE

Thursday, December 4, 2014

BYTESM2-Philosophers Stone

Philosophers Stone

Given below code is for BYTESM2 spoj or Philosophers Stone spoj

Hint:- Simple DP 




#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int h , m;
        cin>>h>>m;
        int arr[h+9][m+9];
        for(int i = 0 ; i < h ; i++)
            for(int j = 0 ; j < m ; j++)
                cin>>arr[i][j];
        int ma = -1;
        for(int i = 0 ; i < m ; i++)
            ma = max(ma , arr[0][i]);
        for(int i = 1 ; i < h ; i++)
        {
            ma = -1;
            for(int j = 0 ; j < m ; j++)
            {
                if(j>0 && j<m-1)
                    arr[i][j] = max(arr[i-1][j] + arr[i][j] , max(arr[i-1][j-1]+arr[i][j] , arr[i-1][j+1]+arr[i][j]));
                else if(j>0)
                    arr[i][j] = max(arr[i-1][j]+arr[i][j] ,arr[i-1][j-1]+arr[i][j]);
                else if(j<m-1)
                    arr[i][j] = max(arr[i-1][j]+arr[i][j],arr[i-1][j+1]+arr[i][j]);
                ma = max(arr[i][j] , ma);
            }
        }
        cout<<ma<<endl;
    }
    return 0;
}

3 comments:

  1. #include
    using namespace std;

    int findmax(int a,int b,int c)
    {
    int max=a;

    if(max>d[i][j];
    for(j=1;j<=w;j++)
    dp[1][j]=d[1][j];
    //storing inf value
    for(i=1;i<h;i++)
    dp[i][0]=-1;
    //recurrence relation
    for(i=2;i<=h;i++)
    for(j=1;j<=w;j++)
    dp[i][j]=d[i][j]+findmax(dp[i-1][j],dp[i-1][j+1],dp[i-1][j-1]);

    //answer
    int ans=dp[h][1];
    for(j=2;j<=w;j++)
    if(ans<dp[h][j])
    ans=dp[h][j];

    printf("%d\n",ans);


    }
    }
    Why this answer is wrong

    ReplyDelete
  2. #include
    using namespace std;

    int findmax(int a,int b,int c)
    {
    int max=a;

    if(max>d[i][j];
    for(j=1;j<=w;j++)
    dp[1][j]=d[1][j];
    //storing inf value
    for(i=1;i<h;i++)
    dp[i][0]=-1;
    //recurrence relation
    for(i=2;i<=h;i++)
    for(j=1;j<=w;j++)
    dp[i][j]=d[i][j]+findmax(dp[i-1][j],dp[i-1][j+1],dp[i-1][j-1]);

    //answer
    int ans=dp[h][1];
    for(j=2;j<=w;j++)
    if(ans<dp[h][j])
    ans=dp[h][j];

    printf("%d\n",ans);


    }
    }

    ReplyDelete

Your comment is valuable to us