题解:AT_agc063_f [AGC063F] Simultaneous Floor
[AGC063F] Simultaneous Floor
给定两个非负整数的有序数对
(a_1,a_2),(b_1,b_2) ,定义一次操作为:
- 选择一个正实数
x ,将(a_1,a_2) 变为(\lfloor a_1x\rfloor,\lfloor a_2x\rfloor) 。求能否将
(a_1,a_2) 变为(b_1,b_2) ,如果能,求出最小操作次数。多组数据。
T\le 10^5,0\le a_1,a_2,b_1,b_2\le 10^9
参考了官方题解,但是有一些证明是自己证的。如果证明部分有错误,请联系我更改。
前置知识:Stern–Brocot 树,以及在 Stern–Brocot 树上二分,比如 P8058 这个题。
先判掉答案为
我们将
我们的大体思路为,求出哪些点能通过
考虑哪些点能通过一次操作到达
于是一次能够到达
接下来考虑求出哪些点能通过两次操作到达
接下来三次,四次......操作能到达的点的集合也可以类似求出。设
接下来考虑如何快速求
我们可以先找出这个
可以发现,如果
当一个点往右儿子走时,设这个点的分数为
于是我们就证明了上面的结论,那么每次在 Stern–Brocot 树上二分,就可以快速从
首先,递推结束时,
因为根到
于是暴力递推即可,总复杂度为
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define ll long long
#define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
using namespace std;
const int N = 1e5+5;
struct node
{
ll p,q;
node d(){return {q,p};}
friend bool operator < (const node &x,const node &y)
{return x.p*y.q < y.p*x.q;}
friend bool operator == (const node &x,const node &y)
{return x.p*y.q == y.p*x.q;}
};
node get(node l,node r)
{
node x = {0,1},y = {1,0};
while(1)
{
node s = {x.p+y.p,x.q+y.q};
if(l < s&&s < r)return s;
if(l < s)
{
ll k = (y.p*r.q-r.p*y.q)/(r.p*x.q-x.p*r.q);
y = {x.p*k+y.p,x.q*k+y.q};
}
else
{
ll k = (l.p*x.q-x.p*l.q)/(y.p*l.q-l.p*y.q);
x = {x.p+y.p*k,x.q+y.q*k};
}
}
}
node query(node l,node r)
{
node x = get(l,r);
if(x.q == 1)x.p = (r.p-1)/r.q;
return x.p++,x;
}
int solve(ll a1,ll a2,ll b1,ll b2)
{
node p = {a1,a2};
if(a1 == b1&&a2 == b2)return 0;
if(!b1&&!b2)return 1;
if(!a1&&b1||!a2&&b2)return -1;
if(!b1)return a1<a2?p<node{1,b2}?1:2:-1;
if(!b2)return a2<a1?node{b1,1}<p?1:2:-1;
node l = {b1,b2+1},r = {b1+1,b2};
for(int t = 1;;t++)
{
if(l < p&&p < r)return t;
node x = query(r.d(),l.d()).d(),y = query(l,r);
if(x == l&&y == r)return -1;
l = x;r = y;
}
}
char buf[1<<21],*p1,*p2;
inline int rd()
{
char c;int f = 1;
while(!isdigit(c = getchar()))if(c=='-')f = -1;
int x = c-'0';
while(isdigit(c = getchar()))x = x*10+(c^48);
return x*f;
}
int main()
{
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
for(int t = rd();t--;)
{
ll a1 = rd(),a2 = rd(),b1 = rd(),b2 = rd();
printf("%d\n",solve(a1,a2,b1,b2));
}
return 0;
}