跳到正文

题解

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

Northwolf1约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年9月14日
收录
2026年9月20日
更新
2026年9月21日
篇幅
约 3 分钟
题目
P11442

版本

  1. v2当前
  2. v1

简要思路

网格大小为 N=2nN=2^n。两种遍历方式都是对 2k×2k2^k\times2^k 网格的递归划分。

光栅遍历:从左到右、从上到下依次编号,编号 xx 对应坐标:

  • 行:x/Nx / N。
  • 列:x%Nx \% N。

Z 字型遍历:把 2k×2k2^k\times2^k 网格横竖各分两半,四个子块按左上、右上、左下、右下顺序遍历,每个子块内部也按同样规则递归。

Z 编号 → 坐标

从最大块开始,每层:

  • 当前块边长一半为 h=2k−1h=2^{k-1},子块大小 b=h2b=h^2。
  • x / b 得到子块编号:0 左上、1 右上、2 左下、3 右下。
  • x %= b 进入子块继续。
  • 根据子块编号累加坐标偏移:右上的列加 h,左下的行加 h,右下行列都加 h。

坐标 → Z 编号

从最大块开始,每层:

  • 根据当前坐标 (r,c)(r,c) 判断在哪个子块:
    • 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:

C++
#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;
}
原文