hdu1247 Hat’s Words(字典树)

判断某一个单词是否可以由另外两个单词组合而成,如果是则输出。


把所有单词边读入边插入字典树,树中值同样为某单词是否出现。然后遍历每个单词,再暴力求某单词是否由其他两个组成。由于只有一组数据,所以不存在什么超时爆内存。思路很清晰。

#include 
#include 
#include 
#include 
#include 

using namespace std;

typedef long long LL;

const int N = 30;
const int INF = 1e8;

struct Trie
{
    int sum;
    Trie *next[26];
    Trie()
    {
        sum = 0;
        for(int i = 0; i < 26; i ++)
            next[i] = 0;
    }
}*root;

int ans;

void inserttrie(Trie *p, char *str)
{
    int k = 0;
    while(str[k] != '\0')
    {
        int id = str[k] - 'a';
        if(p -> next[id] == 0)
        {
            p -> next[id] = new Trie;
        }
        p = p -> next[id];
        k ++;
    }
    if(p -> sum == 0) ans ++;
    p -> sum ++;//该单词是否出现过
}

int findtrie(Trie *p, char *str)
{
    int k = 0, num = 0;
    while(str[k] != '\0')
    {
        int id = str[k] - 'a';
        if(p -> next[id])
        {
            p = p -> next[id];
            num = p -> sum;
            k ++;
        }
        else return 0;
    }
    return num;
}

int main()
{
  //  freopen("in.txt", "r", stdin);
    char s[50005][N], a[N], b[N];
    int countt = 0;
    root = new Trie;
    while(~scanf("%s", s[countt]))
    {
        inserttrie(root, s[countt]);
        countt ++;
    }
    for(int i = 0; i < countt; i ++)
    {
        int len = strlen(s[i]), flag = 0;
        for(int j = 0; j < len; j ++)
        {
            memset(a, 0, sizeof(a));
            memset(b, 0, sizeof(b));
            int pos1 = 0, pos2 = 0;
            for(int l = 0; l < j; l ++)
            {
                a[pos1 ++] = s[i][l];
            }
            for(int l = j; l < len; l ++)
            {
                b[pos2 ++] = s[i][l];
            }
            if(findtrie(root, a) && findtrie(root, b)) flag = 1;
        }
        if(flag) printf("%s\n", s[i]);
    }
    return 0;
}


你可能感兴趣的:(hdu,数据结构-各种树)