Luogu: P2004 territory selection (prefix and,)

topic:

Insert picture description here

analysis:

I think it’s more complicated, do dp between the same size,

When seeing the problem solution, first calculate the rectangle starting from 1, 1, and suddenly thought of doing it on the leetcode, and then combining the image, it is easy to find dp.

Insert picture description here

Code:

#include<bits/stdc++.h>
using namespace std;
int A[1001][1001];
long long A1[1001][1001];//从(0,0)开始 
int a,b,c;//行 列  方形大小 
//自己想的比较复杂,相同大小之间进行dp,
//当看到题解先计算从1,1,开始的矩形,突然就想到了在leetcode上做过,再结合图像,很容易发现dp。 
int main()
{
    
    
 cin>>a>>b>>c;
 for(int i=0;i<a;i++) for(int j=0;j<b;j++) cin>>A[i][j];
 //A1 初始化
 A1[0][0]=A[0][0];
 for(int i=1;i<b;i++) A1[0][i]=A1[0][i-1]+A[0][i];
 for(int i=1;i<a;i++) A1[i][0]=A1[i-1][0]+A[i][0]; 
 for(int i=1;i<a;i++)
 for(int j=1;j<b;j++)
 {
    
    
  A1[i][j]=A1[i-1][j]+A1[i][j-1]-A1[i-1][j-1]+A[i][j];
 }
 /*
 for(int i=0;i<a;i++)
 {
  for(int j=0;j<b;j++)
  {
   cout<<A1[i][j]<<' ';
  }
  cout<<endl;
 }
 */
 long long maxx=A1[c-1][c-1];
 int aa=c-1,bb=c-1;
 for(int i=c;i<a;i++)
 {
    
    
  if(A1[i][c-1]-A1[i-c][c-1]>maxx)
  {
    
    
   maxx=max(maxx,A1[i][c-1]-A1[i-c][c-1]);
   aa=i;bb=c-1;
  }
 }
 for(int i=c;i<b;i++)
 {
    
    
  if(A1[c-1][i]-A1[c-1][i-c]>maxx)
  {
    
    
   maxx=max(maxx,A1[c-1][i]-A1[c-1][i-c]);
   aa=c-1;bb=i;
  }
 }
 for(int i=c;i<a;i++)
 for(int j=c;j<b;j++)
 {
    
    
  if(A1[i][j]-A1[i-c][j]-A1[i][j-c]+A1[i-c][j-c]>maxx)
  {
    
    
   maxx=max(maxx,A1[i][j]-A1[i-c][j]-A1[i][j-c]+A1[i-c][j-c]);
   aa=i;bb=j;
  }
 }
 cout<<aa-c+2<<' '<<bb-c+2;
}

Guess you like

Origin blog.csdn.net/weixin_42721412/article/details/108539710