您的位置:首页 > 其它

hdu 4099 Revenge of Fibonacci

2013-11-04 19:42 429 查看
暴力求出前十万的斐波那契数列,然后存储起来,后面再查找就好了。

存储的话建议两种方式,一种是字典树,一种是hash,当然这个题目用字典树会更好。

#include <iostream>
#include <cstdio>
#include <cstring>
#pragma comment(linker, "/STACK:36777216")
using namespace std;
const int mod=10;
struct add
{
int size;
int a[100000];
add()
{
memset(a,0,sizeof(a));
size=0;
}
void operator +(add & xx)
{
int l=max(1,size-100);
int r=max(size,xx.size);
for(int i=l;i<=r;i++)
{
xx.a[i]+=a[i];
xx.a[i+1]+=xx.a[i]/mod;
xx.a[i]%=mod;
}
if(xx.a[xx.size+1]) xx.size++;
for(int i=l;i<=xx.size;i++)
{
swap(xx.a[i],a[i]);
}
swap(size,xx.size);
}
}now,next;
struct
{
int next[10],ans;
}trie[4000010];
int lon;

int a[50],c[10];

void push(int ans)
{
int t=0;
int ff=1;
for(int i=now.size;i>=1&&ff<=40;i--,ff++)
{
if(trie[t].next[now.a[i]]==-1)
{
trie[t].next[now.a[i]]=++lon;
trie[lon].ans=ans;
}
t=trie[t].next[now.a[i]];
}
}

int main()
{
//    freopen("in.txt","r",stdin);
memset(trie,-1,sizeof(trie));
lon=0;
now.a[1]=1,now.size=1;
next.a[1]=1,next.size=1;
push(1);
push(2);
for(int i=1;i+2<=100000;i++)
{
now+next;
push(i+2);
}
int T,tt=0;
scanf("%d",&T);
char a[50];
getchar();
while(T--)
{
char tmp;
int n=0;
while(scanf("%c",&tmp),tmp!='\n')
{
if(tmp!=' ')
a[++n]=tmp;
}
int t=0;
bool flag=true;
for(int i=1;i<=n;i++)
{
if(trie[t].next[a[i]-'0']==-1)
{
flag=false;
break;
}
t=trie[t].next[a[i]-'0'];
}
printf("Case #%d: ",++tt);
if(!flag) printf("-1\n");
else printf("%d\n",trie[t].ans-1);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: