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

Sunday, July 27, 2014

MFISH-Catch Fish

Below given c++ code is for MFISH spoj or Catch Fish spoj
Hint:- Think Dynamic,
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n,m,b,d,flag=0,flag1=0,pre=0;
    scanf("%d",&n);
    int array[n],pos[n],dp[n];
    for (int i=0; i<n; i++)
        pos[i]=0,dp[i]=0;
    for (int i=0; i<n; i++)
        scanf("%d",&array[i]);
    scanf("%d",&m);
    for (int i=0; i<m; i++)
    {
        scanf("%d %d",&b,&d);
        pos[b-1]=d;
    }
    for (int i=0; i<n; i++)
    {
        if (pos[i]!=0)
        {
            int sum=0,j,l=max(pre,i-pos[i]+1);
            for (j=l; j<min(l+pos[i],n); j++)
                sum+=array[j];
            int k=j;
            if (!flag)
            {
                dp[min(l+pos[i]-1,n-1)]=sum;
                flag=1;
            }
            else
                dp[min(l+pos[i]-1,n-1)]=sum+dp[l-1];
            for (j=min(l+pos[i],n); j<min(n,i+pos[i]); j++)
            {
                sum=(sum+array[j]-array[j-pos[i]]);
                dp[j]=max(dp[j-1],dp[j-pos[i]]+sum);
            }
            pre=k;
        }
        else if (i>0)
            dp[i]=max(dp[i],dp[i-1]);
    }
    printf("%d\n",dp[n-1]);
    return 0;
}

No comments:

Post a Comment

Your comment is valuable to us