zoukankan      html  css  js  c++  java
  • Shortest Prefixes

    http://poj.org/problem?id=2001

    View Code
    #include<stdio.h>
    #include<string.h>
    #include<malloc.h>
    struct trie
    {
        bool isstr ;
        int num ;
        trie *next[26] ;
    } ;
    void insert(trie *root, char *s)
    {
        int i ;
        if(root==NULL||*s=='\0')
        return ;
        trie *p = root ;
        while(*s)
        {
            if(p->next[*s-'a']==NULL)
            {
                trie *q = (trie*)malloc(sizeof(trie)) ;
                for(i=0; i<26; i++)
                q->next[i] = NULL ;
                q->isstr = false ;
                q->num = 1 ;
                p->next[*s-'a'] = q ;
                p = p->next[*s-'a'] ;
            }
            else
            {
                p = p->next[*s-'a'] ;
                p->num++ ;
            }
            s++ ;
        }
        p->isstr = true ;
    }
    void search(trie *root, char *s)
    {
        trie *p = root ;
        while(p&&*s)
        {
            if(p->next[*s-'a']->num==1)
            {
                printf("%c", *s) ;
                return ;
            }
            else
            printf("%c",*s) ;
            p = p->next[*s-'a'] ;
            s++ ;
        }
    }
    void del(trie *root)
    {
        int i ;
        for(i=0; i<26; i++)
        {
            if(root->next[i]!=NULL)
            {
                del(root->next[i]) ;
            }
        }
        delete root ;
    }
    int main()
    {
        //freopen("a.txt","r",stdin);
        int i ;
        char s[1010][25] ;
        trie *root = (trie*)malloc(sizeof(trie)) ;
        for(i=0; i<26; i++)
        root->next[i] = NULL ;
        root->isstr = false ;
        root->num = 1 ;
        int n = 0 ;
        while(gets(s[n]))
        {
            insert(root, s[n]) ;
            n++ ;
        }
        int t = 0 ;
        while(t<n)
        {
            printf("%s ",s[t]) ;
            search(root, s[t]) ;
            printf("\n") ;
            t++ ;
        }
        del(root) ;
        return 0 ;
    }
  • 相关阅读:
    Python生成器表达式
    Python列表解析
    Python迭代器(Iterator)
    Python set 集合
    python eval 函数妙用
    Python字典 (dict)
    Python序列之元组 (tuple)
    Python序列之列表 (list)
    递归和反射
    常用标准库
  • 原文地址:https://www.cnblogs.com/yelan/p/2994171.html
Copyright © 2011-2022 走看看