(字典树)Revenge of Fibonacci -- HDU -- 4099

链接:

http://acm.hdu.edu.cn/showproblem.php?pid=4099

要用c++交哦, G++ MLE

不是很懂,先粘上慢慢学习

代码:

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

#define N 100

struct node
{
    int ID;
    node *next[10];
}*Head;

char c[100], str[3][100];


void Add(char a[], char b[], char back[]) ///计算a+b, 结果存入c
{
    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] = '';
}


void Tree_Insert(char str[], int Index)///插入单词
{
    node *t, *s = Head;
    int i;
    int len = strlen(str);

    for(i=0; i<len && i<41; i++)
    {
        int id = str[i]-'0';
        if(s->next[id]==NULL)
        {
            t = new node();
            for(int i=0;i<10;i++)t->next[i]=NULL;
            t->ID = -1;
            s->next[id] = t;
        }
        s = s->next[id];
        if(s->ID<0) s->ID = Index;
    }
}

int Tree_Find(char str[])
{
    node *s=Head;
    int count, i;
    int len = strlen(str);

    for(i=0; i<len; i++)
    {
        int id = str[i]-'0';
        if(s->next[id]==NULL)
            return -1;
        else
        {
            s = s->next[id];
            count = s->ID;
        }
    }
    return count;
}

void Tree_Del(node *p)
{
    for(int i=0; i<10; i++)
    {
        if(p->next[i]!=NULL)
            Tree_Del(p->next[i]);
    }
    free(p);
}

int main()
{
    Head = new node();
    for(int i=0;i<10;i++)Head->next[i]=NULL;

    Head->ID = -1;
    str[0][0] = '1';
    str[0][1] = 0;
    Tree_Insert(str[0], 0);

    str[1][0]='1';
    str[1][1]=0;
    Tree_Insert(str[1], 1);

    for(int i=2; i<100000; i++)
    {
        int len1 = strlen(str[0]);
        int len2 = strlen(str[1]);

        if(len2>60)
        {
            str[1][len2-1]=0;
            str[0][len1-1]=0;
        }
        Add(str[0], str[1], str[2]);

        ///  printf("%s
",str[2]);

        Tree_Insert(str[2], i);
        strcpy(str[0], str[1]);
        strcpy(str[1], str[2]);

        ///   for(int i=0;i<100;i++)str[0][i]=str[1][i];
        ///   for(int i=0;i<100;i++)str[1][i]=str[2][i];
    }

    int t, iCase=1;
    char str1[60];
    scanf("%d", &t);
    while(t--)
    {
        scanf("%s", str1);
        printf("Case #%d: %d
", iCase++, Tree_Find(str1));
    }

    Tree_Del(Head);
    return 0;
}
勿忘初心
原文地址:https://www.cnblogs.com/YY56/p/4740577.html