HDU 1247

思路:年前学得Trie树,当时没过,可能当时没完全理解吧,今天碰到了,就凭着理解直接敲的,调了两次终于过了,把每个单词结尾标记为1,查询的时候看某个单词的子串是否存在,这题WA点不少,必须搞清判断条件。


 
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
class Node{
    public:
        int cnt;
        Node *child[26];
        Node(){
            cnt = 0;
            for(int i = 0;i < 26;i ++) child[i] = NULL;
        }
};
Node *root = new Node();
char str[50005][111];
void Update(char *str){
    Node *tmp = root;
    while(*str != '\0'){
        if(tmp->child[*str-'a'] == NULL){
            Node *p = new Node();
            tmp->child[*str-'a'] = p;
        }
        tmp = tmp->child[*str-'a'];
        str++;
    }
    tmp->cnt = 1;
}
bool Judge(char *str){
    Node *tmp = root;
    while(*str != '\0'){
        if(tmp->child[*str-'a'] == NULL) return false;
        tmp = tmp->child[*str-'a'];
        str++;
    }
    return tmp->cnt == 1;
}
int main(){
    int n = 0;
//    freopen("in.cpp","r",stdin);
    memset(str,0,sizeof(str));
    while(~scanf("%s",str[n])) Update(str[n]),n++;
    for(int i = 0;i < n;i ++){
        int len = strlen(str[i]);
        char tmp1[111],tmp2[111];
        memset(tmp1,0,sizeof(tmp1));
        memset(tmp2,0,sizeof(tmp2));
        for(int j = 1;j < len;j ++){
            int p = 0;
            for(int k = 0;k < j;k ++) tmp1[p++] = str[i][k];
            p = 0;
            for(int k = j;k < len;k ++) tmp2[p++] = str[i][k];
            if(Judge(tmp1) && Judge(tmp2)) {
                printf("%s\n",str[i]);
                break;
            }
            memset(tmp1,0,sizeof(tmp1));
            memset(tmp2,0,sizeof(tmp2));
        }
    }
    return 0;
}

posted on 2014-04-30 18:39  wangzhili  阅读(103)  评论(0编辑  收藏  举报