动态字典树_拆分查找(HDU_1247)

#include <stdio.h>
#include <string.h>

#define M 26
#define WordSize 32
#define WordCount 50000

struct node{
    int end;
    node *child[M];
    node()
    {
        end = 0;
        memset(child,NULL,sizeof(child));
    }
};

char map[WordCount][WordSize];

void insert(node *root, char *str)
{
    node *p = root;
    int len = strlen(str);
    for(int i=0; i<len; i++)
    {
        int k = str[i] - 'a';
        if(p->child[k] == NULL)
            p->child[k] = new node;
        p = p->child[k];
    }
    p->end = 1;
}

int find(node *root, char *str)
{
    node *p = root;
    int len = strlen(str);
    for(int i=0; i<len; i++)
    {
        int k = str[i] - 'a';
        if(p->child[k] == NULL)
            return 0;
        p = p->child[k];
    }
    return p->end;
}

int cutFind(node *root, char *str)
{
    int len = strlen(str);
    for(int i=1; i<len; i++)
    {
        if(find(root,str + i))    ;
        else    continue;
        char ch = str[i];
        str[i] = '\0';
        if(find(root,str))
        {
            str[i] = ch;
            return 1;
        }
        str[i] = ch;
    }
    return 0;
}


int main(int argc, char* argv[])
{
    #ifdef __MYLOCAL
    freopen("in.txt","r",stdin);
    #endif

    node *root = new node;
    int n = 0;
    while(scanf("%s",map[n]) != EOF)
    {
        insert(root,map[n]);
        n++;
    }
    for(int i=0; i<n; i++)
    {
        cutFind(root,map[i]) == 1 ? printf("%s\n",map[i]) : NULL;
    }

    return 0;
}

 

posted on 2013-07-22 22:06  lk1993  阅读(205)  评论(0编辑  收藏  举报