sgu 175. Encoding 二分模拟

本文介绍了一个特殊的字符串编码算法,并提供了一种方法来确定经过该算法编码后的字符在新字符串中的位置。通过递归的方式将原始字符串进行编码转换,并讨论了如何高效地找到特定字符在编码后字符串中的确切位置。

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

175. Encoding
time limit per test: 0.25 sec.
memory limit per test: 4096 KB
input: standard
output: standard



Let phi(W) is the result of encoding for algorithm: 
1. If the length of W is 1 then phi(W) is W; 
2. Let coded word is W = w1w2...wN and K = N / 2 (rounded down); 
3. phi(W) = phi(wNwN-1...wK+1) + phi(wKwK-1...w1). 
For example, phi('Ok') = 'kO', phi('abcd') = 'cdab'. 
Your task is to find position of letter wq in encoded word phi(W).

Input
Given integers N, q (1 <= N <= 10^9; 1<= q <= N), where N is the length of word W.

Output
Write position of letter wq in encoded word phi(W).

Sample test(s)

Input
9 4
Output
8



#include <bits/stdc++.h>
using namespace std;
typedef long long ll;




int main(){
    int n,q;
    scanf("%d%d",&n,&q);
    int a=n,b=1;
    int l=1,r=n;
    while(l<r){
//        cout<<l<<" "<<r<<endl;
//        cout<<a<<" "<<b<<endl;
        int c=(l+r)/2;
        int w=(r-l+2)/2;
        if(a<b){
            if(q<=a+w-1){
                r=c;
                b=a+w-1;
                swap(a,b);
            }
            else{
                l=c+1;
                a=a+w;
                swap(a,b);
            }
        }
        else{
            if(q>=a-w+1){
                r=c;
                b=a-w+1;
                swap(a,b);
            }
            else{
                l=c+1;
                a=a-w;
                swap(a,b);
            }
        }
    }
    printf("%d",l);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值