题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1859
题目大意:求矩阵中任意子矩阵中的最小值.
题目思路:二维线段树.
对于这题更新相当于是单点的,所以树套树的线段树应该会比矩形树更快.
因为不懂得树套树如何对整个区间的更新(和这题没关系),所以我写二维线段树,一般都采用矩形树.
代码:
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <ctype.h> #include <math.h> #include <time.h> #include <stack> #include <queue> #include <map> #include <set> #include <vector> #include <string> #include <iostream> #include <algorithm> using namespace std; //#define ull unsigned __int64 //#define ll __int64 //#define ull unsigned long long //#define ll long long #define son1 New(p.xl,xm,p.yl,ym),(rt<<2)-2 #define son2 New(p.xl,xm,min(ym+1,p.yr),p.yr),(rt<<2)-1 #define son3 New(min(xm+1,p.xr),p.xr,p.yl,ym),rt<<2 #define son4 New(min(xm+1,p.xr),p.xr,min(ym+1,p.yr),p.yr),rt<<2|1 #define lson l,mid,rt<<1 #define rson mid+1,r,rt<<1|1 #define middle (l+r)>>1 #define MOD 1000000007 #define esp (1e-8) const int INF=0x3F3F3F3F; const double DINF=10000.00; //const double pi=acos(-1.0); const int N=310; int n,m; int mmin[(N<<2)*(N<<2)]; int mtx[N][N]; struct node{ int xl,xr,yl,yr; int xmid(){return (xl+xr)>>1;} int ymid(){return (yl+yr)>>1;} }; node New(int xl,int xr,int yl,int yr){ node r; r.xl=xl,r.xr=xr; r.yl=yl,r.yr=yr; return r; } void PushUp(int rt){ int t1=min(mmin[(rt<<2)-2],mmin[(rt<<2)-1]); int t2=min(mmin[rt<<2],mmin[rt<<2|1]); mmin[rt]=min(t1,t2); } void Build(node p,int rt){ if(p.xl==p.xr && p.yl==p.yr){ mmin[rt]=mtx[p.xl][p.yl]; return; } int xm=p.xmid(),ym=p.ymid(); Build(son1);Build(son2); Build(son3);Build(son4); PushUp(rt); } int Query(node p,int rt,node P){ if((P.xl<=p.xl&&p.xr<=P.xr)&&(P.yl<=p.yl&&p.yr<=P.yr)) return mmin[rt]; int xm=p.xmid(),ym=p.ymid(),ret=INF; if(P.xl<=xm){ if(P.yl<=ym) ret=min(ret,Query(son1,P)); if(ym<P.yr) ret=min(ret,Query(son2,P)); } if(xm<P.xr){ if(P.yl<=ym) ret=min(ret,Query(son3,P)); if(ym<P.yr) ret=min(ret,Query(son4,P)); } return ret; } int main(){ //freopen("1.in","r",stdin); //freopen("1.out","w",stdout); int i,j,k,r1,c1,r2,c2; int T,cas;scanf("%d",&T);for(cas=1;cas<=T;cas++){ scanf("%d",&n); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&mtx[i][j]); Build(New(1,n,1,n),1); scanf("%d",&m); while(m--){ scanf("%d%d%d%d",&r1,&c1,&r2,&c2); if(r1>r2) swap(r1,r2); if(c1>c2) swap(c1,c2); printf("%d\n",Query(New(1,n,1,n),1,New(r1,r2,c1,c2))); } } return 0; }