Meaning of the title: the n * n matrix, you can select a sub-matrix k * k, and then all the sub-matrix B all into W, ask how you select this sub-matrix so that the resulting matrix in a row W is a full or maximum number of all columns of W
Solution: Consider each row and each column for a particular row, the order to let it all become W, then the upper left corner of the endpoint sub-matrix is in a range, so we can put a value in the range of plus each 1
In order to do two-dimensional differential speed selection, the final answer is the maximum value of the matrix
This question can be used as a two-dimensional differential template
#include<bits/stdc++.h> #define forn(i, n) for (int i = 0; i < int(n); i++) #define fore(i, s, t) for (int i = s; i < (int)t; i++) #define fi first #define se second #define ll long long using namespace std; const int maxn=2e5+5; const int inf=2e9; int dif[2005][2005];//difference array //from (x1,y1) (x2,y2) add val void add(int x1,int y1,int x2,int y2,int val){ dif[x1][y1]+=val; dif[x1][y2+1]-=val; dif[x2+1][y1]-=val; dif[x2+1][y2+1]+=val; } string s[maxn]; int main () { int n,k; cin>>n>>k; for(int i=0;i<n;i++){ cin>>s[i]; } int res=0; for(int i=0;i<n;i++){ you l = -1, r = -1; for(int j=0;j<n;j++){ if(s[i][j]=='B') { if(l==-1) l=j; r=j; } } if(l==-1) { res++; continue; } if(r-l+1>k) continue; add(max(1,i-k+2),max(1,r-k+2),i+1,l+1,1); } for(int j=0;j<n;j++){ int l=-1,r=-1; for(int i=0;i<n;i++){ if(s[i][j]=='B') { if(l==-1) l=i; r=i; } } if(l==-1) { res++; continue; } if(r-l+1>k) continue; add(max(1,r-k+2),max(j-k+2,1),l+1,j+1,1); } int ans=0; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ dif[i][j]=dif[i][j]+dif[i-1][j]+dif[i][j-1]-dif[i-1][j-1]; ans=max(ans,dif[i][j]); } } printf("%d\n",ans+res); }