【bzoj2144】跳跳棋 lca+二分+模拟gcd

3 篇文章 0 订阅
1 篇文章 0 订阅

AC通道:http://www.lydsy.com/JudgeOnline/problem.php?id=2144

【题解】
一道关于lca+二分+模拟gcd的神题,蒟蒻不得不偷窥了题解
在序列上一共有2种操作:
中间可以往两侧跳
两侧仅有一个能往中间跳
那么所有的状态就能表示为一棵二叉树,第一种情况为其两个儿子,第二种为其父亲
问题转换为给定树上的两个结点,求其距离
我们发现若记前两个数差t1,后两个数差t2,不妨设t1<t2
则左边最多往中间跳(t2-1)/t1次
然后只能右边往中间跳,是一个辗转相除的过程,即在logK的时间内我们可以用这种方法得到某个结点它向上K次后的结点,或者根节点,同时还可以顺便算下深度
那么只要求始终两个状态的深度d1,d2,将较深的调整到同一深度
然后二分/倍增求与lca的深度差x
ans=2*x+abs(d1-d2)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<ctime>
#include<algorithm>
using namespace std;
#define INF 1000000000
struct node{int v[5];}root1,root2;
int temp,temp1,temp2,ans,a[5],b[5];
inline int read()
{
    int x=0,f=1;  char ch=getchar();
    while(!isdigit(ch))  {if(ch=='-')  f=-1;  ch=getchar();}
    while(isdigit(ch))  {x=x*10+ch-'0';  ch=getchar();}
    return x*f;
}
node dfs(int p[],int k)
{
    node ans;
    for(int i=1;i<=3;i++)  ans.v[i]=p[i];
    int t1=p[2]-p[1],t2=p[3]-p[2];
    if(t1==t2)  return ans;
    if(t1<t2)
    {
        int step=min(k,(t2-1)/t1);
        k-=step;  temp+=step;
        ans.v[1]+=step*t1;  ans.v[2]+=step*t1;
    }
    if(t1>t2)
    {
        int step=min(k,(t1-1)/t2);
        k-=step;  temp+=step;
        ans.v[2]-=step*t2;  ans.v[3]-=step*t2;
    }
    if(k)  return dfs(ans.v,k);
    else return ans;
}
bool operator!=(node a,node b){for(int i=1;i<=3;i++)if(a.v[i]!=b.v[i])return 1;return 0;}
int main()
{
    freopen("cin.in","r",stdin);
    freopen("cout.out","w",stdout);
    for(int i=1;i<=3;i++)  a[i]=read();
    for(int i=1;i<=3;i++)  b[i]=read();
    sort(a+1,a+4);  sort(b+1,b+4);
    root1=dfs(a,INF);  temp1=temp;  temp=0;
    root2=dfs(b,INF);  temp2=temp;  temp=0;
    if(root1!=root2)  {printf("NO\n");  return 0;}
    if(temp1>temp2)
    {
        swap(temp1,temp2);
        for(int i=1;i<=3;i++)swap(a[i],b[i]);
    }
    ans=temp2-temp1;
    root1=dfs(b,ans);
    for(int i=1;i<=3;i++)b[i]=root1.v[i];
    int l=0,r=temp1;
    while(l+1<r)
    {
        int mid=(l+r)/2;
        if(dfs(a,mid)!=dfs(b,mid))  l=mid;
        else r=mid;
    }
    if(dfs(a,l)!=dfs(b,l))  temp=r;
    else temp=l;
    printf("YES\n%d\n",ans+2*temp);
    return 0;
}


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值