整体二分。直接while就可以啊。。。好像复杂度确实是对的。。。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #define maxn 250050 using namespace std; struct pnt { int x,y,val; }p[maxn]; struct query { int x1,y1,x2,y2,id,k; }q[maxn]; int n,m,x,t[550][550],cnt=0,ans[maxn],id[maxn],mx=0,T=0,tmp[maxn]; bool vis[maxn]; bool cmp(pnt x,pnt y) { return x.val<y.val; } int lowbit(int x) {return (x&(-x));} 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)) t[i][j]+=val; } int ask(int x,int y) { int ret=0; for (int i=x;i>=1;i-=lowbit(i)) for (int j=y;j>=1;j-=lowbit(j)) ret+=t[i][j]; return ret; } int find(int x) { return ask(q[x].x2,q[x].y2)-ask(q[x].x1-1,q[x].y2)-ask(q[x].x2,q[x].y1-1)+ask(q[x].x1-1,q[x].y1-1); } void solve(int l,int r,int L,int R) { if (l==r) return; if (L>R) return; int mid=l+r>>1,l1,l2,ret=0; while ((p[T+1].val<=mid) && (T<cnt)) {add(p[T+1].x,p[T+1].y,1);T++;} while ((p[T].val>mid) && (T>=1)) {add(p[T].x,p[T].y,-1);T--;} for (int i=L;i<=R;i++) { int now=find(id[i]); if (now>q[id[i]].k-1) {vis[i]=true;ans[id[i]]=mid;ret++;} else vis[i]=false; } l1=L;l2=L+ret; for (int i=L;i<=R;i++) { if (vis[i]) tmp[l1++]=id[i]; else tmp[l2++]=id[i]; } for (int i=L;i<=R;i++) id[i]=tmp[i]; solve(l,mid,L,l1-1);solve(mid+1,r,l1,l2-1); } int main() { scanf("%d%d",&n,&m); for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) { scanf("%d",&x); cnt++;mx=max(mx,x); p[cnt].x=i;p[cnt].y=j;p[cnt].val=x; } sort(p+1,p+cnt+1,cmp); for (int i=1;i<=m;i++) { scanf("%d%d%d%d%d",&q[i].x1,&q[i].y1,&q[i].x2,&q[i].y2,&q[i].k); q[i].id=i; } for (int i=1;i<=m;i++) id[i]=i; solve(0,mx+1,1,m); for (int i=1;i<=m;i++) printf("%d\n",ans[i]); return 0; }