您的位置:首页 > 其它

bzoj2656 数列 高精度&递推

2016-01-23 21:55 246 查看
原来想hash的,后来发现没有这么复杂。

我们不妨考虑一对数(x,x+1),那么它的结果可以由(x/2,x/2+1)的结果得到,这里的/与c++里的一样表示整除,后面也是如此。有两种情况:

1.x=2u,x+1=2u+1,则Ax=Ax/2,A(x+1)=Ax/2+A(x/2+1);

2.x=2u+1,x+1=2u+2,则Ax=Ax/2+A(x/2+1),Ax+1=A(x/2+1);

然后所有的数对最终会变为(1,2),且复杂度为O(logN)。结果即(n,n+1)的前一项。注意多组数据清零,以及n=0时特判(其实不特判也不是不可以)。

AC代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

struct hgnum{ int p[505]; }s,x,y; char ch[105]; int c[1005];
hgnum pls(hgnum a,hgnum b){
int i; a.p[0]=max(a.p[0],b.p[0]);
for (i=1; i<=a.p[0]; i++) a.p[i]+=b.p[i];
for (i=1; i<=a.p[0]; i++) if (a.p[i]>9){
a.p[i+1]+=a.p[i]/10; a.p[i]%=10;
}
if (a.p[a.p[0]+1]) a.p[0]++; return a;
}
void hlf(){
int i;
for (i=s.p[0]; i; i--){
if (s.p[i]&1 && i>1) s.p[i-1]+=10; s.p[i]>>=1;
}
if (!s.p[s.p[0]]) s.p[0]--;
}
void clr(hgnum &a){ memset(a.p,0,sizeof(a.p)); }
int main(){
int cas; scanf("%d",&cas);
while (cas--){
scanf("%s",ch+1); int i,len=0;
clr(s); clr(x); clr(y); s.p[0]=strlen(ch+1);
for (i=1; i<=s.p[0]; i++) s.p[i]=ch[s.p[0]-i+1]-'0';
if (s.p[0]==1 && !s.p[1]){ puts("0"); continue; }
while (s.p[0]>1 || s.p[1]>1){ c[++len]=s.p[1]&1; hlf(); }
x.p[0]=x.p[1]=y.p[0]=y.p[1]=1;
for (i=len; i; i--) if (c[i]) x=pls(x,y); else y=pls(x,y);
for (i=x.p[0]; i; i--) printf("%d",x.p[i]); puts("");
}
return 0;
}


by lych

2016.1.23
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: