Saturday, 5 May 2012

UVa 108 Maximum Sum Solution

#include<iostream>
#include<list>
#include<string>
#include<cstring>
#include<sstream>
#include<cctype>
#include<string.h>
#include<algorithm>
#include<cmath>
#include<stack>
#include<fstream>
#include<cstdlib>
#include<vector>
#include<map>
#include<utility>
#include<iomanip>
#include<queue>
using namespace std;
#define clr(a) memset(a,0,sizeof(a))
#define PB push_back
#define pi acos(-1.0)
#define eps 1e-9
long sum[120][120];

int main()
{
int n,a,b,c,d,arr[120][120];
long max,temp;
while(cin>>n)
        {
            max=0;
            for(a=1;a<=n;a++)
                for(b=1;b<=n;b++)
                    cin>>arr[a][b];

            for(a=1;a<=n;a++)
                for(b=1;b<=n;b++)
                    for(c=1;c<=a;c++)
                        for(d=1;d<=b;d++)
                            sum[a][b]+=arr[c][d];

            for(a=0;a<=n;a++)
                for(b=0;b<=n;b++)
                    for(c=0;c<=a;c++)
                        for(d=0;d<=b;d++)
                            {
                                temp=sum[a][b]-sum[a][d]-sum[c][b]+sum[c][d];
                                if(temp>max)
                                max=temp;
                            }
            cout<<max<<endl;
            clr(sum);
        }
return 0;
}

2 comments:

  1. #include
    #define max(a,b) a>b ? a:b
    using namespace std;

    int row[110][110],mat[110][110],n,m;

    int func(int start, int end)
    {
    int i,j,curnt=0, mx=-1270000;
    for(i=1;i<=n;i++)
    {
    j=row[i][end]-row[i][start-1];
    curnt+=j;
    if(curnt>mx) mx=curnt;
    if(curnt<0) curnt=0;
    }
    return mx;
    }

    int main()
    {
    int i,j,temp;
    while(cin>>n)
    {
    for(i=0;i<=n;i++)
    {
    row[i][0]=0;
    }
    for(i=1;i<=n;i++)
    {
    for(j=1;j<=n;j++)
    {
    cin>>mat[i][j];
    row[i][j]=row[i][j-1]+mat[i][j];
    }
    }

    temp=-12700000;
    for(i=1;i<=n;i++)
    {
    for(j=i;j<=n;j++)
    {
    temp=max(temp,func(i,j));
    }
    }
    cout<<temp<<endl;
    }
    return 0;
    }

    ReplyDelete
  2. could you please explain the logic..i cannot understand the code :(

    ReplyDelete