Codeforces 897C Nephren gives a riddle(递归模拟)

题意:

给你一些字符串:

A: [What are you doing at the end of the world? Are you busy? Will you save us?]

B: [What are you doing while sending "]

C: ["? Are you busy? Will you send "]

D: ["?]

(中括号内为给出的字符串,问号、引号、空格也算在内)

定义字符串f[0] = A,递推式f[n] = B + f[n-1] + C + f[n-1] + D

比如:

f[0] = [What are you doing at the end of the world? Are you busy? Will you save us?]

f[1] = [What are you doing while sending "What are you doing at the end of the world? Are you busy? Will you save us?"? Are you busy? Will you send "What are you doing at the end of the world? Are you busy? Will you save us?"?]

然后有q个询问,每个询问有两个整数n,k,让你输出f[n]的第k个字符。如果f[n]没有第k个字符,则输出'.'。

题解:

模拟好题,递归处理。

定义la,lb,lc,ld分别代表字符串A,B,C,D的长度:

la=75, lb=34, lc=32, ld=2

定义len[i]为字符串f[i]的长度,很容易推出len[i] = (2^i)*la + (2^i - 1)*(lb + lc + ld)。

因为len[i]有可能很大,而k只有10^18,所以当i>=54的时候,直接返回一个很大的数就行了(比如9e18)。

对于每个询问,先判断是否k >= len[n]。如果是,直接输出'.'。

否则就从后往前推位置。

因为f[n] = B + f[n-1] + C + f[n-1] + D

所以当前位置k在f[n]中的位置有5种情况:

(1)k在B中,即k∈[1, lb]

(2)k在第一个f[n-1]中,即k∈[lb+1, lb+len[n-1]]

(3)k在C中,即k∈[lb+len[n-1]+1, lb+len[n-1]+lc]

(4)k在第二个f[n-1]中,即k∈[lb+len[n-1]+lc+1, lb+len[n-1]*2+lc]

(5)k在D中,即k∈[lb+len[n-1]*2+lc+1, lb+len[n-1]*2+lc+ld]

对于情况1,3,5,找到k在B,C,D中对应的位置,输出即可:

(1)k不变

(3)k -= lb+len[n-1]

(5)k -= lb+len[n-1]*2+lc

对于情况2,4,将k变成在f[n-1]中的位置,继续执行这种变换即可。

(2)k -= lb

(4)k -= lb+len[n-1]+lc

最多变换n次,所以总复杂度为O(qn)。

参考https://www.cnblogs.com/Leohh/p/7966971.html

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6+5;
char f0[] = "What are you doing at the end of the world? Are you busy? Will you save us?";
char f[] = "What are you doing while sending \"\"? Are you busy? Will you send \"\"?";

ll len[N];
void init() {
    len[0] = strlen(f0);
    ll l = strlen(f);
    for(int i = 1; i <= 53; ++i)
        len[i] = len[i-1]*2 + l;
    for(int i = 54; i <= 100000; ++i) len[i] = 9e18;
}

char ans[20];
char dfs(int n,ll k) {
    if(n == 0) {
        if(k < len[0])return f0[k];
        else return '.';
    }
    ///分类讨论
    if(k < 34)return f[k];
    k -= 34;
    if(k < len[n-1]) return dfs(n-1,k);
    k -= len[n-1];
    if(k < 32)return f[k+34];
    k -= 32;
    if(k < len[n-1]) return dfs(n-1,k);
    k -= len[n-1];
    if(k < 2)return f[k+66];
    return '.';
}

int n,q;
ll k;
int main() {
    init();
    scanf("%d",&q);
    for(int i = 0; i < q; ++i) {
        scanf("%d%lld",&n,&k);
        k--;
        ans[i] = dfs(n,k);
    }
    ans[q] = '\0';
    printf("%s\n",ans);
    return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值