Description
There is a matrix of a*b integers, now ask you to find a n*n square area, so that the maximum and minimum values of all the numbers in the region
The difference is minimal.
Input
The first behavior is 3 integers, which represent the value of A,b,n the second row to the a+1 line each behavior b nonnegative integer, representing the number in the corresponding position in the matrix. Every
Rows are separated by a space between two adjacent numbers.
100% of Data 2<=a,b<=1000,n<=a,n<=b,n<=100
Output
Only one integer, which is the minimum value of the difference between the maximum and minimum integers in all the n*n square areas in the a*b matrix.
Sample Input5 4 2
1 2 5 6
0 17 16 0
16 17 2 1
2 10 2 1
1 2 2 2Sample Output1HINTSourceSolution
began to want to use two-dimensional $st$ table, check the puzzle found that there is less complexity,,,
Since the length and width of the matrix are limited to $n$, there is a sense of the maximum minimum value of the sliding window.
Calculates the maximum minimum value of each point starting at the left $n$ Point, and uses a monotone queue for the exercise to find the most value
Each point is then calculated as the maximum minimum value of the $n*n$ matrix in the lower-right corner, using the value just calculated, and using the monotone queue to find the most value for the column.
So we're out. The maximum value of the corresponding rectangle for each point minus the minimum value
1#include <bits/stdc++.h>2 using namespacestd;3 intq[1005], c[1005][1005], r[4][1005][1005];4 intMain ()5 {6 intA, B, N, front, back, ans =1000000000;7scanf"%d%d%d", &a, &b, &n);8 for(inti =1; I <= A; ++i)9 for(intj =1; J <= B; ++j)Tenscanf"%d", &c[i][j]); One for(inti =1; I <= A; ++i) A { -Front = back =0; - for(intj =1; J <= B; ++j) the { - if(Front! = back && J-q[front +1] ==N) -++Front; - while(Front! = back && C[i][j] <=C[i][q[back]]) +--Back ; -Q[++back] =J; +r[0][I][J] = C[i][q[front +1]]; A } atFront = back =0; - for(intj =1; J <= B; ++j) - { - if(Front! = back && J-q[front +1] ==N) -++Front; - while(Front! = back && C[i][j] >=C[i][q[back]]) in--Back ; -Q[++back] =J; tor[1][I][J] = C[i][q[front +1]]; + } - } the for(intj = N; J <= B; ++j) * { $Front = back =0;Panax Notoginseng for(inti =1; I <= A; ++i) - { the if(Front! = back && I-q[front +1] ==N) +++Front; A while(Front! = back && r[0][I][J] <= r[0][q[back]][j]) the--Back ; +Q[++back] =i; -r[2][I][J] = r[0][q[front +1]][j]; $ } $Front = back =0; - for(inti =1; I <= A; ++i) - { the if(Front! = back && I-q[front +1] ==N) -++Front;Wuyi while(Front! = back && r[1][I][J] >= r[1][q[back]][j]) the--Back ; -Q[++back] =i; Wur[3][I][J] = r[1][q[front +1]][j]; - } About } $ for(inti = n; I <= A; ++i) - for(intj = N; J <= B; ++j) -ans = min (ans, r[3][I][J]-r[2][i][j]); -printf"%d\n", ans); A return 0; +}
View Code
[BZOJ1047] [HAOI2007] ideal square (monotone queue)