简要思路
网格大小为 。两种遍历方式都是对 网格的递归划分。
光栅遍历:从左到右、从上到下依次编号,编号 对应坐标:
- 行:。
- 列:。
Z 字型遍历:把 网格横竖各分两半,四个子块按左上、右上、左下、右下顺序遍历,每个子块内部也按同样规则递归。
Z 编号 → 坐标
从最大块开始,每层:
- 当前块边长一半为 ,子块大小 。
x / b得到子块编号:0 左上、1 右上、2 左下、3 右下。x %= b进入子块继续。- 根据子块编号累加坐标偏移:右上的列加 h,左下的行加 h,右下行列都加 h。
坐标 → Z 编号
从最大块开始,每层:
- 根据当前坐标 判断在哪个子块:
r<h && c<h:左上,偏移 0。r<h && c>=h:右上,偏移 b,然后c-=h。r>=h && c<h:左下,偏移 2b,然后r-=h。- 否则:右下,偏移 3b,然后
r-=h; c-=h。
- 累加偏移,进入子块继续。
坐标 → 光栅编号
光栅编号为 r*N+c。
code:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,m,N;
pair<ll,ll>zt(ll x){
ll r=0,c=0;
for(ll k=n;k>=1;k--){
ll h=1LL<<(k-1);
ll b=h*h;
ll d=x/b;
x%=b;
if(d==0){
}else if(d==1){
c+=h;
}else if(d==2){
r+=h;
}else{
r+=h;
c+=h;
}
}
return{r,c};
}
ll tz(ll r,ll c){
ll a=0;
for(ll k=n;k>=1;k--){
ll h=1LL<<(k-1);
ll b=h*h;
if(r<h&&c<h){
}else if(r<h&&c>=h){
a+=b;
c-=h;
}else if(r>=h&&c<h){
a+=2*b;
r-=h;
}else{
a+=3*b;
r-=h;
c-=h;
}
}
return a;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin>>n>>m;
N=1LL<<n;
while(m--){
char o;
ll x;
cin>>o>>x;
if(o=='Z'){
auto[r,c]=zt(x);
ll a=r*N+c;
cout<<a<<'\n';
}else{
ll r=x/N;
ll c=x%N;
ll a=tz(r,c);
cout<<a<<'\n';
}
}
return 0;
}