题解:P11683 [Algo Beat Contest 001 E] Experiments on Collatz

· · 题解

最后 30min 的时候进去的,做了这一个题就走了,感觉很忍俊不禁。

首先看到询问 2 的范围是 10^7,考虑直接把 10^7 以内打表出来。打表的过程可以采用记忆化,如果这个位置是 10^7 以内就用数组存一下,这样可以省去很多步骤。

通过打表我们发现 10^7 以内的最大 f 值已经到达了询问一的 685,且打表中途涉及到的最大数也没有超过 10^{18} 范围,而且打表速度还很快。

所以我们第一个询问预处理出来 686 个答案,第二个询问预处理前缀积即可。算的时候需要算逆元。

打表复杂度不知道(反正能过,大概是 O(n) 多一些?),预处理复杂度 O(n),询问复杂度 O(q\log n)。

#include<bits/stdc++.h>
#define int long long
#define N 10000005
using namespace std;
signed q,g[N],ans[700],mul[N],ff[N];
const int mod=1145141923;
int f(int x){
    if(x<=1e7&&(ff[x]||x==1))return ff[x];
    if(x%2){
        if(x<=1e7)return ff[x]=f(x*3+1)+1;
        else return f(x*3+1)+1;
    }
    else{
        if(x<=1e7)return ff[x]=f(x/2)+1;
        return f(x/2)+1;
    }
}
int qpow(int x,int y){
    int ans=1;
    while(y){
        if(y&1)ans=ans*x%mod;
        x=x*x%mod;y>>=1;
    }
    return ans;
}
signed main(){
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    ff[1]=0;mul[1]=1;
    for(int i=2;i<=1e7;++i)f(i),g[i]=max(g[i-1],ff[i]),mul[i]=1ll*mul[i-1]*ff[i]%mod;int n=1e7;
    for(int i=0;i<=685;++i)ans[i]=lower_bound(g+1,g+n+1,i)-g;
    cin>>q;
    while(q--){
        int op,x,l,r;
        cin>>op;
        if(op==1)cin>>x,cout<<ans[x]<<"\n";
        else{
            cin>>l>>r;
            if(l==1)cout<<"0\n";
            else cout<<mul[r]*qpow(mul[l-1],mod-2)%mod<<'\n';
        }
    }
    return 0;
}