数据挺水
直接排序复杂度有点高,可以二分中位数
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <ctype.h>
#include <vector>
#include <algorithm>
#include <time.h>
// cout << " === " << endl;
using namespace std;
typedef long long ll;
const int maxn = 800 + 7;
const ll INF = 0x3f3f3f3f3f3f3f3f, mod = 1e9+7;
int n, m, t;
int a[maxn][maxn];
void init() {
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= n; ++j)
scanf("%d", &a[i][j]);
}
}
void solve() {
int x1, x2, y1, y2;
for(int i = 0; i < m; ++i) {
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
int cnt = (x2-x1+1)*(y2-y1+1);
t = (cnt+1)/2 - 1;
ll l_ = INF, r_ = -INF;
int mid, ans;
for(int i = x1; i <= x2; ++i) {
for(int j = y1; j <= y2; ++j)
l_ = min(l_, (ll)a[i][j]), r_ = max(r_, (ll)a[i][j]);
}
l_ = (int)l_, r_ = (int)r_;
while(l_ <= r_) {
int num = 0;
mid = (l_ + r_) / 2;
for(int i = x1; i <= x2; ++i) {
for(int j = y1; j <= y2; ++j)
if(a[i][j] < mid) num++;
}
if(num <= t) {
l_ = mid+1;
ans = mid;
}
else if(num > t) r_ = mid-1;
}
printf("%d\n", ans);
}
}
int main() {
init();
solve();
return 0;
}