AcWing98 分形之城 (递归)

题目链接:https://www.acwing.com/problem/content/100/

为方便运算,城市编号从(0)开始,
按城市分级递归求解(D)编号城市的坐标
注意变换后坐标的计算(坐标从((0,0))开始)

四舍五入用(%0lf)即可

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll,ll> P;

const int maxn = 40;

int T;
int N;
ll A,B;

double dis(P a, P b){ return (double)sqrt(1.0 * (a.first - b.first) * (a.first - b.first) + 1.0 * (a.second - b.second) * (a.second - b.second)) * 10; }

P dfs(int n,ll pos){
	if(n == 0){ return make_pair(0, 0); }
	ll len = 1ll << (n - 1), num = 1ll << (2 * n - 2);
	P tp = dfs(n - 1, pos % num);
	ll x = tp.first, y = tp.second;
	
	int d = pos / num;
	if(d == 0) return make_pair(y, x);
	if(d == 1) return make_pair(x, y + len);
	if(d == 2) return make_pair(x + len, y + len);
	if(d == 3) return make_pair(2 * len - y - 1, len - x - 1);
}

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
	T = read();
	while(T--){
		N = read(), A = read(), B = read(); --A, --B;
		++N;
		
		ll num = 1ll << (2 * N - 2);
		P a = dfs(N - 1, A % num);
		P b = dfs(N - 1, B % num);
//		printf("%lld %lld %lld %lld
",a.first, a.second, b.first, b.second); 
		printf("%.0lf
",dis(a, b));
	}
	
	return 0;
}
原文地址:https://www.cnblogs.com/tuchen/p/13909922.html