Given a mxn matrix. Print the largest sum that can be obtained from a kxk submatrix.
Code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<set>
#include<map>
using namespace std;
int A[100][100];
int S[100][100];
int KS[100][100];
int main()
{
int m,n,k,i,j,maxs=0,s=0;
cin>>m>>n>>k;
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
cin>>A[i][j];
}
for(i=1;i<=m;i++)
{
for(j=1;j<=k;j++)s+=A[i][j];
S[i][1]=s;
s=0;
}
for(i=1;i<=n;i++)
{
for(j=2;j<= n-k+1; j++)
S[i][j]=S[i][j-1]-A[i][j-1] + A[i][j+k-1];
}
for(j=1;j<=n;j++)
{
for(i=1;i<=k;i++) s+=S[i][j];
KS[1][j]=s;
s=0;
}
for(i=2;i<=m-k+1;i++)
{
for(j=1;j<=n-k+1;j++)
{
KS[i][j]=KS[i-1][j]-S[i-1][j]+S[i+k-1][j];
}
}
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
if(KS[i][j]>maxs) maxs=KS[i][j];
}
}
cout<<maxs<<endl;
return 0;
}
Code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<string>
#include<set>
#include<map>
using namespace std;
int A[100][100];
int S[100][100];
int KS[100][100];
int main()
{
int m,n,k,i,j,maxs=0,s=0;
cin>>m>>n>>k;
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
cin>>A[i][j];
}
for(i=1;i<=m;i++)
{
for(j=1;j<=k;j++)s+=A[i][j];
S[i][1]=s;
s=0;
}
for(i=1;i<=n;i++)
{
for(j=2;j<= n-k+1; j++)
S[i][j]=S[i][j-1]-A[i][j-1] + A[i][j+k-1];
}
for(j=1;j<=n;j++)
{
for(i=1;i<=k;i++) s+=S[i][j];
KS[1][j]=s;
s=0;
}
for(i=2;i<=m-k+1;i++)
{
for(j=1;j<=n-k+1;j++)
{
KS[i][j]=KS[i-1][j]-S[i-1][j]+S[i+k-1][j];
}
}
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
if(KS[i][j]>maxs) maxs=KS[i][j];
}
}
cout<<maxs<<endl;
return 0;
}
No comments:
Post a Comment