Given an n*n matrix A, whose entries Ai,j are integer numbers ( 1 <= i <= n, 1 <= j <= n ). An operation FIND the minimun number in a given ssub-matrix.
Input
The first line of the input contains a single integer T , the number of test cases.
For each test case, the first line contains one integer n (1 <= n <= 300), which is the sizes of the matrix, respectively. The next n lines with n integers each gives the elements of the matrix.
The next line contains a single integer N (1 <= N <= 1,000,000), the number of queries. The next N lines give one query on each line, with four integers r1, c1, r2, c2 (1 <= r1 <= r2 <= n, 1 <= c1 <= c2 <= n), which are the indices of the upper-left corner and lower-right corner of the sub-matrix in question.
Output
For each test case, print N lines with one number on each line, the required minimum integer in the sub-matrix.
Sample Input
1
2
2 -1
2 3
2
1 1 2 2
1 1 2 1
Sample Output
-1
2
题意:T组数据,每组数据输入一个n*n的矩阵,再输入q个子矩阵,输出子每个矩阵中最小的元素。
每个矩阵建立一个结构体数组,将其对应的x,y坐标及其值val存入,按val的大小将结构体排序,对于每一子矩阵,从小到大搜索找到满足在(lx,lr)到(rx,ry)范围的子矩阵中最小的元素便为所求的最小元素。
代码如下:
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
struct maxi
{
int x, y, val;
} ma[90000+2];
int cmp(const void *a, const void *b)
{
maxi *aa = (maxi*)a;
maxi *bb = (maxi*)b;
return aa->val - bb->val;
}
int main()
{
#ifdef test
freopen("in.txt", "r", stdin);
#endif
int t, n, q, lx, ly, rx, ry;
scanf("%d", &t);
while(t--)
{
scanf("%d",&n);
int num = 0;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
{
ma[num].x = i;
ma[num].y = j;
scanf("%d", &ma[num].val);
num++;
}
qsort(ma, num, sizeof(ma[0]), cmp); //按val值排序
scanf("%d", &q);
while(q--)
{
scanf("%d%d%d%d", &lx, &ly, &rx, &ry);
for(int i = 0; i < num; i++)
if((ma[i].x >= lx) && (ma[i].y >= ly) && (ma[i].x <= rx) && (ma[i].y <= ry)) //找在子矩阵中最小的元素
{
printf("%d\n", ma[i].val);
break;
}
}
}
return 0;
}

本文介绍了一种针对大规模矩阵的快速搜索算法,旨在高效找出指定子矩阵内的最小元素值。通过预先处理矩阵元素并按值排序,结合特定查询条件,实现对子矩阵最小值的有效检索。
491





