yyc_ @ 2023-03-30 11:29:21
/*YYC is Thinking Here*/
#include<bits/stdc++.h>
#define deb(var) //cerr<<"deb: "<< #var <<'='<<(var)<<'\n'
#define mids(l,r) const auto mid = l + r >> 1
#define lb(x) x&-x
#define cint const int&
#define int long long
#define inf 0x3f3f3f3f3f3f3f3f
using namespace std;
const int maxn = 2e3+10,maxm = 1e6+10;
struct num{ int v,i,j; }val[maxn][maxn];
struct ask{ int i1,j1,i2,j2,k,ans; }qs[maxm];
vector<num*> a;
vector<ask*> q;
int h[maxn][maxn],sh[maxn * maxn],shc,k,n,m;
int bit[maxn][maxn];
inline void add(int x,int y) {
for(int i = x;i<=n;i += lb(i))
for(int j = y;j<=n;j += lb(j))
++bit[i][j];
}
inline void sub(int x,int y) {
for(int i = x;i<=n;i += lb(i))
for(int j = y;j<=n;j += lb(j))
++bit[i][j];
}
inline int get(int x,int y) {
int ans = 0;
for(int i = x;i;i ^= lb(i)) for(int j = y;j;j ^= lb(j))ans += bit[i][j];
deb(x);deb(y);deb(ans);
return ans;
}
void sol(int l,int r,vector<num*> a,vector<ask*> q) {
deb(l);deb(r);for(auto && val : q) deb(val->k);
if(l == r) {
for(auto&& qs : q) qs->ans = l;
return;
}
const int mid = l + r >> 1;
vector<num*> a1,a2; //a1 <= mid;
for(auto&& val : a)
if(val->v <= mid) a1.push_back(val);
else a2.push_back(val);
for(auto&& val : a) if(val->v <= mid) add(val->i,val->j);
vector<ask*> q1,q2;
deb(mid);
for(auto&& qs : q) {
int less = get(qs->i2,qs->j2) - get(qs->i2,qs->j1 - 1) - get(qs->i1 - 1,qs->j2) + get(qs->i1 - 1,qs->j1 - 1);
deb(qs->k);deb(less);
if(qs->k <= less) q1.push_back(qs);
else qs->k -= less,q2.push_back(qs);
}
for(auto&& val : a) if(val->v <= mid) sub(val->i,val->j);
if(!q1.empty())sol(l,mid,a1,q1);
if(!q2.empty()) sol(mid+1,r,a2,q2);
}
signed main() {
int i1,i2,j1,j2;
ios::sync_with_stdio(0),cin.tie(0);
// ifstream ifs(".in");
// ofstream ofs(".out");
// cin.rdbuf(ifs.rdbuf()),cout.rdbuf(ofs.rdbuf());
cin>>n>>m;
for(int i = 1;i<=n;++i)
for(int j = 1;j<=n;++j) cin>>h[i][j],sh[++shc] = h[i][j];
sort(sh+1,sh+shc+1); shc = unique(sh+1,sh+shc+1) - sh - 1;
deb(shc);
for(int i = 1;i<=n;++i)
for(int j = 1;j<=n;++j) {
val[i][j] = {lower_bound(sh+1,sh+shc+1,h[i][j]) - sh,i,j};
deb(val[i][j].v);
a.push_back(&val[i][j]);
}
for(int i = 1;i<=m;++i) {
cin>>i1>>j1>>i2>>j2>>k;
qs[i] = {i1,j1,i2,j2,k,0};
q.push_back(&qs[i]);
}
sol(1,shc,a,q);
for(int i = 1;i<=m;++i) cout<<sh[qs[i].ans]<<'\n';
}
/*
* I love it all
* Go forward,move forward !
*/
不清楚错哪里了......