B. Black Squaretime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.
You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length.
InputThe first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet.
The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white.
OutputPrint the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1.
Examplesinput5 4
WWWW
WWWB
WWWB
WWBB
WWWWoutput5input1 2
BBoutput-1input3 3
WWW
WWW
WWWoutput1NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).
In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.
In the third example all cells are colored white, so it's sufficient to color any cell black.
先找出最长b距离,再判断是否可以实现。
AC代码:
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 const int INF=1<<30; 5 6 char mp[110][110]; 7 int maxx=0,maxy=0,minx=INF,miny=INF; 8 9 int main(){ 10 int n,m; 11 cin>>n>>m; 12 int ans=0,t=n*m; 13 for(int i=0;i<n;i++){ 14 for(int j=0;j<m;j++){ 15 cin>>mp[i][j]; 16 if(mp[i][j]=='B'){ 17 ans++; 18 maxx=max(i,maxx); 19 maxy=max(j,maxy); 20 minx=min(i,minx); 21 miny=min(j,miny); 22 } 23 } 24 } 25 if(ans==t){ 26 if(n==m) 27 cout<<0<<endl; 28 else 29 cout<<-1<<endl; 30 } 31 else if(ans==0){ 32 cout<<1<<endl; 33 } 34 else{ 35 int temp=maxx-minx+1; 36 int temp2=maxy-miny+1; 37 int cnt=max(temp,temp2); 38 // cout<<cnt<<endl; 39 int res=cnt*cnt-ans; 40 if(cnt<=min(n,m)) 41 cout<<res<<endl; 42 else 43 cout<<-1<<endl; 44 } 45 return 0; 46 }