fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. String[]size=(in.readLine().trim()).split("\\s+");
  14. int rows=Integer.parseInt(size[0]);
  15. int colums=Integer.parseInt(size[1]);
  16. int[][]matrix=new int[rows][colums];
  17. for (int i = 0; i <rows ; i++) {
  18. String[]elements=(in.readLine().trim()).split("\\s+");
  19. for (int j = 0; j <colums ; j++) {
  20. matrix[i][j]=Integer.parseInt(elements[j]);
  21. }
  22. }
  23. int[][]precomput=precomputation(matrix);
  24. int min=1;
  25. int max=Math.min(rows,colums);
  26. int t=Integer.parseInt(in.readLine().trim());
  27. while (t!=0){
  28. int threshold=Integer.parseInt(in.readLine().trim());
  29. System.out.println(sizeofsquare(precomput,min,max,threshold));
  30. t--;
  31. }
  32. }
  33. static int sizeofsquare(int[][]precomput,int min,int max,int threshold){
  34. while (min<=max){
  35. int mid=min+(max-min)/2;
  36. if (ifpossible(mid,precomput,threshold)) {
  37. if (!ifpossible(mid+1,precomput,threshold)){
  38. return mid;
  39. }else min=mid+1;
  40. }else {
  41. max=mid-1;
  42. }
  43. }
  44. return 0;
  45. }
  46. static boolean ifpossible(int size,int[][]precomput,int threshold){
  47.  
  48. for (int i = 0; i <precomput.length-size ; i++) {
  49. for (int j = 0; j <precomput[i].length-size ; j++) {
  50. if (sum(precomput,i,j,i+size-1,j+size-1)<=threshold){
  51. return true;
  52. }
  53. }
  54. }
  55. return false;
  56. }
  57. static long sum(int[][]precomput,int i1,int j1,int i2,int j2){
  58. long ans=precomput[i2][j2];
  59. if (j1-1>=0) {
  60. ans -= precomput[i2][j1 - 1];
  61. if (i1-1>=0){
  62. ans-=precomput[i1-1][j2];
  63. ans+=precomput[i1-1][j1-1];
  64. }
  65.  
  66. }else {
  67. if (i1-1>=0){
  68. ans-=precomput[i1-1][j2];
  69. }
  70.  
  71. }
  72. return ans;
  73. }
  74. static int[][]precomputation(int[][]arr){
  75. int n=arr.length;
  76. int m=arr[0].length;;
  77. int [][]ans=new int[n][m];
  78. //rowwise
  79. for (int i = 0; i <n ; i++) {
  80. ans[i][0]=arr[i][0];
  81. for (int j = 1; j <m ; j++) {
  82. ans[i][j]=ans[i][j-1]+arr[i][j];
  83. }
  84. }
  85. //columnwise
  86. for (int j = 0; j <m ; j++) {
  87. for (int i = 1; i <n ; i++) {
  88. ans[i][j]+=ans[i-1][j];
  89. }
  90. }
  91. return ans;
  92.  
  93. }
  94. }
Success #stdin #stdout 0.1s 48428KB
stdin
3 7
1 1 3 2 4 3 2
1 1 3 2 4 3 2
1 1 3 2 4 3 2
1
4
stdout
2