您的位置:首页 > 其它

hdu 1671&&poj 3630 Phone List 【字典树】

2015-06-12 02:23 513 查看
题目链接:http://acm.acmcoder.com/showproblem.php?pid=1671

题意:问是否存在一个串是另一个串的前缀。

解法:建字典树,插入的串的结尾设置标志位,如果以后访问到,则存在一个串是另一个串的前缀。注意释放内存,不然超内存;(太弱,释放内存调了好久。。。

代码:

[code]#include <stdio.h>  
#include <iostream>  
#include <string.h>  
#include <algorithm>  
#include <math.h>  
#include <ctype.h>  
#include <time.h>  
#include <queue>  
#include <iterator> 

using namespace std;

typedef struct Trie
{
    int vis;
    Trie *next[10];
}Trie;

Trie *root;
int ok;

void createTrie(char str[])
{
    if (ok) return;
    int len = strlen(str);
    Trie *p = root, *q;
    int id;
    for (int i = 0; i<len; ++i)
    {
        id = str[i] - '0';
        if (p->next[id] == NULL)
        {
            q = new Trie;
            for (int j = 0; j<10; ++j)
                q->next[j] = NULL;

            p->next[id] = q;
            p->next[id]->vis = 1;
            if (i == len-1)
                p->next[id]->vis = -1;
            p = p->next[id];
        }
        else
        {
            if (p->next[id]->vis == -1 || str[i + 1] == '\0')
            {
                ok = 1;
                return;
            }
            if (i == len - 1)
                p->next[id]->vis = -1;
            p = p->next[id];
        }
    }
}

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

char str[1001000];
int t, n;

int main()
{
    scanf("%d",&t);
    while (t--)
    {
        ok = 0;
        root = new Trie;
        for (int i = 0; i < 10; i++)
        {
            root->next[i] = NULL;
            root->vis = 0;
        }
        scanf("%d", &n);
        for (int i = 1; i <= n; i++)
        {
            scanf("%s", str); 
            createTrie(str);
        }
        if (!ok)    puts("YES");
        else puts("NO");
        free_memory(root);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: