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 ;
    }
  • 相关阅读:
    jumpserver安装教程
    正则表达式基础->
    Awk基础
    shell脚本练习题->1
    idea开发工具下载安装教程
    shell 数组基础->
    动荡的国庆前后
    Linux命令之查找
    2013年9月游戏测试总结-文档习惯
    将C#程序做成服务后服务自动停止的问题
  • 原文地址:https://www.cnblogs.com/yelan/p/2994171.html
Copyright © 2011-2022 走看看