hdu 4099 字典树


斐波那契数列 题目要求只有40位 所以加的时候自用保存60位左右就行了这部分用大数相加就行


 题目给的类存虽然很大 但还是超了一次 有个类存清理!!


#include<stdio.h>
#include<string.h>
#include<iostream>
#include<malloc.h>
using namespace std;

struct node
{
    struct node *next[10];
    int flash;
}*root;
char c[100];
int deal(char a[],char b[],char back[])
{

    int i,j,k;
    int x,y,z;
    int up;
    i=strlen(a)-1;
    j=strlen(b)-1;
    k=0;
    up=0;
    while(i>=0||j>=0)
    {
        if(i<0)x=0;
        else x=a[i]-'0';
        if(j<0)y=0;
        else y=b[j]-'0';
        z=x+y+up;
        c[k++]=z%10+'0';
        up=z/10;
        i--;
        j--;
    }
    if(up>0)c[k++]=up+'0';
    for(i=0;i<k;i++)back[i]=c[k-1-i];
    back[k]='\0';
}
int add(char str[],int k)
{
    struct node *p,*q;
    p=root;
    int len=strlen(str);
    for(int i=0;i<len&&i<41;i++)
    {
        if(p->next[str[i]-'0']!=NULL)
        {
            p=p->next[str[i]-'0'];
            if(p->flash==NULL) p->flash=k;
        }
        else 
        {
            q=(struct node*)malloc(sizeof(struct node));
            memset(q,NULL,sizeof(struct node));
            p->next[str[i]-'0']=q;
            p=q;
            p->flash=k;
        }
    }
    return 0;
}
int find(char str[])
{
    struct node *p;
    p=root;
    int len=strlen(str);
    for(int i=0;str[i]!='\0';i++)
    {
        if(p->next[str[i]-'0']==NULL) return -1;
        p=p->next[str[i]-'0'];    
    }
    return p->flash;
}
int clear(node *p)
{
    for(int i=0;i<=9;i++)
    if(p->next[i]!=NULL)
    {
        clear(p->next[i]);
    }
    free(p);
    return 0;
}
int main()
{
    char str1[100],str2[100],str3[100];
    int i,j;
    str1[0]=str2[0]='1';
    str1[1]=str2[1]='\0';
    root=(struct node*)malloc(sizeof(struct node));
    memset(root,NULL,sizeof(struct node));
    add(str1,1);
    for(int k=3;k<100000;k++)
    {
        int len1=strlen(str1);
        int len2=strlen(str2);
        while(len2>51)
        {
            str1[len1--]=0;
            str2[len2--]=0;
        }
        deal(str1,str2,str3);
        add(str3,k);
        int pp=strlen(str3);
        //if(k<=100)    printf("%s\n",str3);
        strcpy(str1,str2);
        strcpy(str2,str3);
    }
    int Q,d=1;
    scanf("%d",&Q);
    char str[50];
    while(Q--)
    {
        scanf("%s",str);
        int t=find(str);
        printf("Case #%d: ",d++);
        if(t<0) printf("-1\n");
        else printf("%d\n",t-1);
    }
    clear(root);
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值