您的位置:首页 > 产品设计 > UI/UE

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

2017-02-16 13:59 453 查看

题意



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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: