题解:P15276 [MCO 2025] Long Binary String
题目大意
给定一个二进制字符串的生成规则:
- 初始为
\tt{1} 。 - 每一秒执行替换:
\tt{1} \to \tt{10} ,\tt{0} \to \tt{1} 。 求执行极长时间后,区间[l, r] 内字符\tt{1} 的个数。其中l, r \le 10^{18} 。
思路分析
由题意明显得这是一个关于斐波那契(Fibonacci)规律的递推题。
如果对斐波那契数列或简单的递归还不太了解的,推荐先去做一下这些基础题:
- P1255 数楼梯
- P1962 斐波那契数列
- P2602 [ZJOI2010] 数字计数(学习数位统计思想)
对递推规律有了一点基础的了解之后,再来看这题就会容易很多。
我们观察字符串的变化:
可以发现:第
因此,字符串的长度
-
len[i] = len[i-1] + len[i-2] -
cnt[i] = cnt[i-1] + cnt[i-2]
问题的解决也并不复杂,对于询问
如何求前缀
还有两个注意点:
- 题目给出的
l, r 高达10^{18} ,普通的int肯定会爆,必须使用unsigned long long。 - 实际上斐波那契数列增长极快,到
90 多项就会超过10^{18} ,所以预处理到溢出为止即可。
最后得出代码:
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
ull len[11111],cnt[11111];
ull count(ull n){
if(n==0) return 0;
int i;
for(i=0;len[i]<=n;i++);
i--;
if(len[i]==n){
return cnt[i];
}
return cnt[i]+count(n-len[i]);
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin>>t;
len[0]=1; cnt[0]=1;
len[1]=2; cnt[1]=1;
int i;
for(i=2;;i++){
len[i]=len[i-1]+len[i-2];
cnt[i]=cnt[i-1]+cnt[i-2];
if(len[i]>(ull)1<<63){
break;
}
}
while(t--){
ull x,y;
cin>>x>>y;
ull ans=count(y)-count(x-1);
cout<<ans<<"\n";
}
return 0;
}