水一发,和区间
k
<script type="math/tex" id="MathJax-Element-18">k</script>小基本一样,不过这个无修改。感觉有修改会很麻烦?
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#define inf 1000000007
using namespace std;
int n,Q,now,cnt;
int tree[505][505];
struct node {int x,y,z;} a[250005];
int ans[60005];
struct query {int x1,x2,y1,y2,k,id;} q[60005],q1[60005],q2[60005];
inline int read()
{
int a=0,f=1; char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1; c=getchar();}
while (c>='0'&&c<='9') {a=a*10+c-'0'; c=getchar();}
return a*f;
}
inline int lowbit(int i)
{
return i&(-i);
}
inline bool operator<(node a,node b)
{
return a.z<b.z;
}
inline void add(int x,int y,int val)
{
for (int i=x;i<=n;i+=lowbit(i))
for (int j=y;j<=n;j+=lowbit(j))
tree[i][j]+=val;
}
inline int query(int x,int y)
{
int tmp=0;
for (int i=x;i;i-=lowbit(i))
for (int j=y;j;j-=lowbit(j))
tmp+=tree[i][j];
return tmp;
}
void solve(int t,int w,int l,int r)
{
if (t>w) return;
if (l==r)
{
for (int i=t;i<=w;i++) ans[q[i].id]=l;
return;
}
int mid=l+r>>1;
while (a[now].z<=mid) now++,add(a[now].x,a[now].y,1);
while (a[now].z>mid) add(a[now].x,a[now].y,-1),now--;
int p1=0,p2=0;
for (int i=t;i<=w;i++)
{
int tmp=query(q[i].x2,q[i].y2)+query(q[i].x1-1,q[i].y1-1)-query(q[i].x1-1,q[i].y2)-query(q[i].x2,q[i].y1-1);
if (tmp>q[i].k-1) q1[++p1]=q[i]; else q2[++p2]=q[i];
}
for (int i=1;i<=p1;i++) q[t+i-1]=q1[i];
for (int i=1;i<=p2;i++) q[t+p1+i-1]=q2[i];
solve(t,t+p1-1,l,mid); solve(t+p1,w,mid+1,r);
}
int main()
{
n=read(); Q=read();
for (int i=1;i<=n;i++)
for (int j=1;j<=n;j++)
a[++cnt].x=i,a[cnt].y=j,a[cnt].z=read();
sort(a+1,a+cnt+1);
a[++cnt].x=1; a[cnt].y=1; a[cnt].z=inf;
for (int i=1;i<=Q;i++)
q[i].x1=read(),q[i].y1=read(),q[i].x2=read(),q[i].y2=read(),q[i].k=read(),q[i].id=i;
solve(1,Q,0,inf);
for (int i=1;i<=Q;i++) printf("%d\n",ans[i]);
return 0;
}