ZOJ 2859 Matrix Searching

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


题意: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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值