【CodeForces】792D Paths in a Complete Binary Tree

本文介绍了一种用于树形结构中快速定位特定节点的算法实现。通过输入节点编号及移动指令,该算法能准确找到目标节点并返回其位置。采用分段逼近的方式逐步缩小搜索范围,适用于大数据量的树状结构导航。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

考虑一下如何方便地表示树中的一个点,模拟即可

#include<stdio.h>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;

ll n,k;
int q,len,tp;
char s[100005];
pair<ll,ll> st[99];

#define mp(a,b) make_pair(a,b)
#define fi first
#define se second
#define poi(a) (a.fi+a.se>>1)


int main()
{
    scanf("%lld%d",&n,&q);
    while (q--)
    {
        scanf("%lld",&k);
        scanf("%s",s);
        len=strlen(s); 
        st[tp=1]=mp(1,n);
        while(poi(st[tp])!=k)
        {
            if (k<poi(st[tp])) st[tp+1]=mp(st[tp].fi,poi(st[tp])-1),tp++;
            if (poi(st[tp])<k) st[tp+1]=mp(poi(st[tp])+1,st[tp].se),tp++;
        }
        for (int i=0;i<len;i++)
        {
            if (s[i]=='U' && poi(st[tp])!=(1+n>>1)) tp--;
            if (s[i]=='L' && st[tp].fi!=st[tp].se) st[tp+1]=mp(st[tp].fi,poi(st[tp])-1),tp++;
            if (s[i]=='R' && st[tp].fi!=st[tp].se) st[tp+1]=mp(poi(st[tp])+1,st[tp].se),tp++;
        }
        printf("%lld\n",poi(st[tp]));
    } 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值