解题报告 CF906D Power Tower

· · 个人记录

题目链接:CF906D Power Tower。

题意:

给定长度为 n 的序列 w[i] ,以及一个数 m ,和 q 个询问,每个询问包括两个参数: l,r ,

对于每个询问,输出 w[l]^{w[l+1]^{w[l+2]^{\cdots^{w[r]}}}}\mod m 。

数据范围:1\leqslant n,q\leqslant10^5,1\leqslant m,w[i]\leqslant 10^9,1\leqslant l,r\leqslant n 。

做法

做法同 P3934 Nephren Ruq Insania 。

都是暴力处理出每次降幂是否加上 phi(p) ,然后递归、快速幂计算。

我的题解:解题报告 P3934 Nephren Ruq Insania 。

两题的不同之处

AC 代码

#include<cstdio>
#include<cstdlib>
#include<cmath>
using namespace std;

namespace Qza {

    int cnt,phi[64];
    int n,q,nowl,nowr;
    long long w[100005],m; 
    bool flag[64];

    int min(int x,int y)
    {
        return x<=y?x:y;
    }
    void Euler(int x) // 暴力算出系列 phi 。 
    {
        int q;
        cnt=0;
        phi[0]=x;
        while(phi[cnt]!=1) {
            ++cnt;
            x=phi[cnt]=phi[cnt-1];
            q=sqrt(phi[cnt]);
            for(int i=2;i<=q;++i) {
                if(!(x%i)) {
                    phi[cnt]-=phi[cnt]/i;
                    while(!(x%i)) x/=i;
                }
            }
            if(x>1) phi[cnt]-=phi[cnt]/x;
        }
        return ;
    }
    void judge(int l,int r,int p)
    {
        int k=cnt;
        for(int i=1;i<=cnt;++i) flag[i]=false;
        int pos=min(r,l+cnt+4); // 注意位数要 5位,虽然写成 l+cnt+3也能 AC。 
        for(int i=l;i<=pos;++i) 
            if(w[i]==1ll) { // 不要写成 w[l] !!! 
                pos=i; break;
            }
        if(pos<l+k) k=pos-l;
        long long now=1ll,sq=1ll;
        while(k>0 && l<=pos) {
            while(k && l+k<=pos) {
                while((sq--) && k) {
                    now=now*w[pos]; 
                    while(now>=phi[k] && k) {flag[k]=true; --k;}
                }
                sq=now; now=1ll;
                --pos;
            }
            --k;
        } 
        return ;
    }
    long long fast_pow(long long x,long long y,int p)
    {
        long long ans=1ll;
        while(y) {
            if(y&1) ans=ans*x%p;
            x=x*x%p; y>>=1;
        }
        return ans%p;
    }
    long long query(int l,int r,int p)
    {
        if(w[l]%p==0) return 0ll;
        if(w[l]==1) return 1ll;
        if(l==r) return w[l]%p;
        int pos=l-nowl+1;
        if(flag[pos]) return fast_pow(w[l],query(l+1,r,phi[pos])+phi[pos],p);
        return fast_pow(w[l],query(l+1,r,phi[pos]),p);
    }
    int read()
    {
        char ch=getchar(); int x=0;
        while(ch<'0' || ch>'9') ch=getchar();
        while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+(ch^48), ch=getchar();
        return x;
    }
    void main()
    {
        n=read(); m=read();
        Euler(m);
        for(int i=1;i<=n;++i) {
            w[i]=read();
        }
        q=read();
        for(int i=1;i<=q;++i) {
            nowl=read(); nowr=read();
            judge(nowl,nowr,m);
            printf("%lld\n",query(nowl,nowr,m)%m);
        }
        return ;
    }
}

int main()
{
    Qza::main();
    return 0;
}