P11442 [Code+#6] 坐标转换 题解

· · 题解

P11442 [Code+#6] 坐标转换 题解

题目传送门

场切の小曲。

题意

rt,虽然看着挺复杂,但实际上很好理解。

分析

一眼推柿子。看到 2^n\times2^n 的网格就莫名地想起递归,试了试是可以的。

把网格每次分成边长为 L 的 4 块,可以发现,对于任意在块中相对位置相同的两个方格 (x_1,y_1),(x_2,y_2)(纵轴为 x,横轴为 y),表示的数 a_1,a_2 有以下关系:

  1. x_1\lt x_2$ 且 $y_1=y_2
a_2=a_1+2\times2^{2L}
  1. x_1\lt x_2$ 且 $y_1\lt y_2
a_2=a_1+3\times2^{2L}
  1. x_1=x_2$ 且 $y_1=y_2
a_2=a_1+0\times2^{2L}
  1. x_1=x_2$ 且 $y_1\lt y_2
a_2=a_1+1\times2^{2L}

相信聪明的你已经看出来如果 x_1\lt x_2 就要加 2^{2L+1};如果 y_1\lt y_2 就要加 2^{2L}。两者的和与左上角那块的值相加即为当前块的值。

实现

对于 Z 函数,比较抽象,需要逆向思维,找到光栅遍历的位置。

pair<ll,ll> z(ll s,ll l,ll f){
    if(l==0) return make_pair(1,1);
    ll len=l-1==0?1:(1<<l-1),len2=len*len,pos=(f-s)/len2;
    auto now=z(s+pos*len2,l-1,f);
    return make_pair(now.first+(pos>>1)*len,now.second+(pos%2)*len);
}

对于 R 函数,可以直接得出位置,带进去找 Z 字型遍历的位置。

ll r(ll sx,ll sy,ll l,ll tx,ll ty){
    if(l==0) return 0;
    ll len=l-1==0?1:(1<<l-1),len2=len*len,pos=(tx-sx)/len*2+(ty-sy)/len,now=r(sx+pos/2*len,sy+(pos%2)*len,l-1,tx,ty);
    return now+pos*len2;
}

::::warning{open}

:::: ## CODE ::::success[AC 代码] ```cpp //场切代码码风比较史,凑合着看吧 #include<bits/stdc++.h> using namespace std; using ll=long long; int m; ll n,num; char op; pair<ll,ll> z(ll s,ll l,ll f){ if(l==0) return make_pair(1,1); ll len=l-1==0?1:(1<<l-1),len2=len*len,pos=(f-s)/len2; auto now=z(s+pos*len2,l-1,f); return make_pair(now.first+(pos>>1)*len,now.second+(pos%2)*len); } ll r(ll sx,ll sy,ll l,ll tx,ll ty){ if(l==0) return 0; ll len=l-1==0?1:(1<<l-1),len2=len*len,pos=(tx-sx)/len*2+(ty-sy)/len,now=r(sx+pos/2*len,sy+(pos%2)*len,l-1,tx,ty); return now+pos*len2; } int main(){ #ifndef ONLINE_JUDGE freopen("trans.in","r",stdin); freopen("trans.out","w",stdout); #endif scanf("%lld%d",&n,&m); while(m--){ scanf("\n%c%lld",&op,&num); if(op=='Z'){ auto p=z(0,n,num); printf("%lld\n",(p.first-1)*(1<<n)+p.second-1); }else if(op=='R') printf("%lld\n",r(1,1,n,num/(1<<n)+1,num%(1<<n)+1)); } return 0; } ``` :::: ##### Update 2025.12.06 删除了部分 $\LaTeX$。