Matrix Searching
Time Limit: 10 Seconds Memory Limit: 32768 KB
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
【题意】
给一个矩阵,计算所给子矩阵内的最小值。
【解题思路】
用结构记录每个元素的位置与值,并根据值的从小到大排序,然后只需遍历这个结构数组,看哪个元素是在所给子矩阵的范围内,若在肯定是最小的,直接break输出即可。
【代码】
#include<bits/stdc++.h>
using namespace std;
const int INF=99999999;
const int maxn=300*300+5;
struct Element
{
int x,y,v;
}a[maxn];
bool cmp(Element a,Element b)
{
return a.v<b.v;
}
int main()
{
int T,n;
scanf("%d",&T);
while(T--)
{
int num=0;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
int x;
scanf("%d",&x);
a[num].x=i;a[num].y=j;
a[num++].v=x;
}
}
sort(a,a+num,cmp);
int m,r1,r2,c1,c2;
scanf("%d",&m);
while(m--)
{
scanf("%d%d%d%d",&r1,&c1,&r2,&c2);
int minv=INF;
for(int i=0;i<num;i++)
{
if(a[i].x>=r1 && a[i].x<=r2 && a[i].y>=c1 && a[i].y<=c2)
{
minv=a[i].v;
break;
}
}
printf("%d\n",minv);
}
}
return 0;
}