[递推] BZOJ2656: [Zjoi2012]数列(sequence)

题意

这里写图片描述
T组询问,每次给定n,输出An。
T<=20, n<=10^100

题解

这道题容易想太多,其实不用对递推式进行什么处理,只需要用特别的方法记忆化即可。
注意到虽然n的范围大,但真正有用的很少。
例如当n=31时:
这里写图片描述
有用的节点只有O(logn)个,如果我们能实现记忆化,可以实现logn的复杂度,再搞个高精即可。
但是数字这么大,如何记忆化呢?实际上从上图我们已经可以发现,只需要一对一对数一起推就可以了。
奇偶讨论往下推
2i+1, 2i ————– i, i+1
2i, 2i-1 ————– i, i-1
这一对数只和下一对数有关,这样推层数就一直是1了。总复杂度O(T*logn*高精)

好像还可以写个STL平衡树把算过的节点放进去,然后二分实现记忆化,复杂度多一个logn。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int con=100000000;
typedef long long LL;
struct Int{
    LL a[505];
    Int(LL x=0){ memset(a,0,sizeof(a)); do a[++a[0]]=x%con, x/=con; while(x); }
    void read(){
        memset(a,0,sizeof(a));
        char s[105]; scanf("%s",s+1); int len=strlen(s+1);
        for(int i=len;i>0;i-=8){ a[0]++; for(int j=max(i-7,1);j<=i;j++) a[a[0]]=a[a[0]]*10+s[j]-'0'; }
    }
    void write(){
        printf("%lld",a[a[0]]);
        for(int i=a[0]-1;i>=1;i--) printf("%08lld",a[i]);
    }
    Int operator + (const Int &b){
        Int c; c.a[0]=max(a[0],b.a[0]);
        for(int i=1;i<=c.a[0];i++) c.a[i]+=a[i]+b.a[i], c.a[i+1]+=c.a[i]/con, c.a[i]%=con;
        if(c.a[c.a[0]+1]) c.a[0]++;
        return c;
    }
    Int operator / (const int &x){
        Int c; c.a[0]=a[0]; 
        LL now=0; for(int i=a[0];i;i--) now=now*con+a[i], c.a[i]=now/x, now%=x;
        c.a[0]=a[0]; if(c.a[0]>1&&!c.a[c.a[0]]) c.a[0]--; 
        return c;
    }
};
void get(Int k1,Int k2,Int &res1,Int &res2){
    if(k1.a[0]==1&&k1.a[1]==0&&k2.a[0]==1&&k2.a[1]==1){
        res1=Int(0); res2=Int(1);
        return;
    }
    get(k1/2,(k2+Int(1))/2,res1,res2);
    if(k1.a[1]&1) res1=res1+res2;
             else res2=res1+res2;
}
int _test;
int main(){
    freopen("bzoj2656.in","r",stdin);
    freopen("bzoj2656.out","w",stdout);
    scanf("%d",&_test);
    while(_test--){
        Int x; x.read();
        Int ans,t; get(x,x+Int(1),ans,t);
        ans.write(); printf("\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值