huangrenheluogu @ 2023-10-19 19:31:01
rt。
#include<bits/stdc++.h>
using namespace std;
const int N = 6e4 + 5;
int n, Q, c[501][501], x, ans[N], LL, RR, tem, nn;
struct data{
int x, y, val;
}a[501 * 501];
inline int lowbit(int x){
return x & -x;
}
inline void add(int x, int y, int val){
for(int i = x; i <= nn; i += lowbit(i)){
for(int j = y; j <= nn; j += lowbit(j)){
c[i][j] += val;
}
}
}
inline int get(int x, int y){
int res = 0;
for(int i = x; i ; i -= lowbit(i)){
for(int j = y; j ; j -= lowbit(j)){
res += c[i][j];
}
}
return res;
}
struct Qu{
int ax, ay, bx, by, k, id;
inline int query(){
return get(bx, by) - get(ax - 1, by) - get(bx, ay - 1) + get(ax - 1, ay - 1);
}
}q[N], b[N];
inline void solve(int l, int r, int L, int R){
if(l == r){
for(int i = L; i <= R; i++) ans[q[i].id] = a[l].val;
return ;
}
int mid = l + r >> 1;
for(int i = l; i <= mid; i++) add(a[i].x, a[i].y, 1);
LL = L - 1, RR = R + 1;
for(int i = L; i <= R; i++){
tem = q[i].query();
if(tem < q[i].k){
q[i].k -= tem;
b[--RR] = q[i];
}
else{
b[++LL] = q[i];
}
}
for(int i = l; i <= mid; i++) add(a[i].x, a[i].y, -1);
for(int i = L; i <= R; i++) q[i] = b[i];
if(LL >= L) solve(l, mid, L, LL);
if(RR <= R) solve(mid + 1, r, RR, R);
}
inline bool cmp(data x, data y){
return x.val < y.val;
}
int main(){
scanf("%d%d", &n, &Q);
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
scanf("%d", &x);
a[(i - 1) * n + j] = (data){i, j, x};
}
}
nn = n;
n *= n;
for(int i = 1; i <= Q; i++){
scanf("%d%d%d%d%d", &q[i].ax, &q[i].ay, &q[i].bx, &q[i].by, &q[i].k);
q[i].id = i;
}
sort(a + 1, a + n + 1, cmp);
solve(1, n, 1, Q);
for(int i = 1; i <= Q; i++) printf("%d\n", ans[i]);
return 0;
}
/*
2 1
2 1
3 4
1 1 2 2 3
*/