CodeForces 846D. Monitor(二維線段樹/二維RMQ)
阿新 • • 發佈:2018-10-31
題目大意:
給予n,m,k,t 和 t 行i,j,val代表第i行j列的元素會在val天后損壞。
求在整張(n*m)圖中求一個k*k的區域的數全部損壞的最小天數。
試了一下二維線段樹,總結一下就是和一維的差別不大,從二叉樹變成了四叉樹(三維線段樹豈不是要八叉樹,喪心病狂)。
總體上就是把一個長方形均分四塊,然後總的節點數就是一個首項為[max(n*m)^2]公比為1/4的等比數列前若干項和,具體比例是多少可以求極限算一下。
空間複雜度基本是O(max(n,m)²)的具體資料如下:
Case | total node | input_n | input_m | total rec | rec/node |
1 | 1398101 | 1024 | 1024 | 1048576 | 75% |
2 | 349525 | 512 | 512 | 262144 | 75% |
3 | 1398099 | 1024 | 512 | 524288 | 37.5% |
4 | 349519 | 500 | 500 | 250000 | 71.53% |
5 | 699051 | 1024 | 1 | 1024 | 0.1465% |
#include <algorithm> #include <iostream> #include <cstring> using namespace std; const int mxn = 250000; #define inf 0x3f3f3f3f inline int son(int p,int x){ return (p<<2)-2+x; } int n,m; struct Interval:public pair<short ,short >{ #define l first #definer second Interval(short a, short b):pair<short ,short >(a,b){} short mid(){ return ((r-l)>>1)+l; } short length(){ return r-l+(short)1; } Interval left(){ return Interval(l,mid()); } Interval right(){ return Interval(mid()+(short)1,r); } bool in(int L,int R){ return l <= L and R <= r; } bool in(const Interval&temp){ return in(temp.l,temp.r); } bool intersect(const Interval &k){ return !( l > k.r || r < k.l ); } void show(){ cerr<<l<<" "<<r<<"\n"; } }; int plant[505][505]; int val[mxn<<2]; void pushUp(int rt){ for(int i = 0 ; i < 4 ; ++i){ val[rt] = max(val[rt],val[son(rt,i)]); } } void buildTree(int rt,Interval x,Interval y){ if(x.length() <= 0 or y.length() <=0)return; if(x.length()==1 and y.length() == 1){ val[rt] = plant[x.l][y.l]; return; } for(int i = 0; i < 4 ; ++i){ buildTree(son(rt,i) , (i&1)?x.right():x.left(),(i&2)?y.right():y.left()); } pushUp(rt); } Interval tarx(0,0),tary(0,0); int Query(int rt,Interval x,Interval y){ if(tarx.in(x) and tary.in(y)){ return val[rt]; } if(!tary.intersect(y) or !tarx.intersect(x))return 0; int ret = 0; for(int i = 0 ; i < 4 ; ++i){ ret = max(ret,Query(son(rt,i) , (i&1)?x.right():x.left(),(i&2)?y.right():y.left())); } return ret; } int Query(short begx, short begy,int k){ tarx = Interval(begx,begx+(short)(k-1)); tary = Interval(begy,begy+(short)(k-1)); return Query(1,Interval(1,n),Interval(1,m)); } int main(){ ios::sync_with_stdio(false); cin>>n>>m; int k,t,x,y,a; cin>>k>>t; memset(plant,0x3f, sizeof(plant)); while (t--){ cin>>x>>y>>a; plant[x][y] = a; } int ans = inf; buildTree(1,Interval(1,n),Interval(1,m)); for(int i = 1 ; i <= n-k+1; ++i){ for(int j = 1 ; j <= m-k+1; ++j){ ans = min(ans,Query(i,j,k)); } } if(ans!=inf){ cout<<ans; }else cout<<-1; }