题目链接:https://vjudge.net/contest/181019#problem/G
题意:给定一个n*n的矩阵,有q次查询,每次查询给定四个数x1 y1 x2 y2,求矩形区域 x1 <= x <= x1, y1 <= y <= y2的中位数。
思路:若每次对小矩形区域内的所有数进行排序找出中位数,则肯定会超时。STL中有一个函数ntn_element(a, x, a + n),用于使数组a中n个数中第x大的数位于第x个位置,x左边的数都大于a[x],x右边的数都小于a[x]但两边的数都可能是无序的。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<cstdlib>
#include<sstream>
#include<deque>
#include<stack>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const double eps = 1e-6;
const int maxn = 1000 + 20;
const int maxt = 300 + 10;
const int mod = 10;
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, -1, 1};
const int Dis[] = {-1, 1, -5, 5};
const int inf = 0x3f3f3f3f;
const int MOD = 1000;
int n, m, k;
int g[maxn][maxn], num[maxn * maxn];
int main(){
int q;
scanf("%d%d", &n, &q);
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
scanf("%d", &g[i][j]);
}
}
int x1, y1, x2, y2;
while(q--){
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
int cnt = 0;
for(int i = x1; i <= x2; ++i){
for(int j = y1; j <= y2; ++j){
num[cnt++] = g[i][j];
}
}
// cout << "cnt == " << cnt << " (cnt - 1) / 2 == " << (cnt - 1) / 2 << endl;
nth_element(num, num + (cnt - 1) / 2 ,num + cnt);
printf("%d\n", num[(cnt - 1) / 2]);
}
return 0;
}