zoukankan      html  css  js  c++  java
  • POJ 2001 Shortest Prefixes(字典树基础)

    题意:给出若干字符串,求每个字符串在所有字符串中唯一的最短前缀;

    思路:将所有串插入字典树,对于每个串枚举前缀,查找唯一前缀;

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    struct node
    {
        int num;
        node *next[26];
    };
    node *head;
    char str[50005][55];
    void init(node *h)
    {
        for(int i=0;i<26;i++)
            h->next[i]=NULL;
        h->num=0;
    }
    void h_insert(char s[])
    {
        node *t,*s1=head;
        int n=strlen(s);
        for(int i=0;i<n;i++)
        {
            int k=s[i]-'a';
            if(s1->next[k]==NULL)
            {
                t=new node;
                init(t);
                s1->next[k]=t;
            }
            s1=s1->next[k];
            s1->num++;
        }
    }
    int h_search(char s[])
    {
        int cnt;
        node *s1=head;
        int n=strlen(s);
        for(int i=0;i<n;i++)
        {
            int k=s[i]-'a';
            if(s1->next[k]==NULL)
                return 0;
            s1=s1->next[k];
            cnt=s1->num;
        }
        return cnt;
    }
    void del(node *h)
    {
        for(int i=0;i<26;i++)
        {
            if(h->next[i])
                del(h->next[i]);
        }
        delete(h);
    }
    char temp[50005];
    int main()
    {
        int i,j,k,len,shu=0;
        head=new node;
        init(head);
        while(scanf("%s",str[shu])!=EOF)
        {
            h_insert(str[shu]);
            shu++;
        }
        for(i=0;i<shu;i++)
        {
            printf("%s ",str[i]);
            memset(temp,0,sizeof(temp));
            len=strlen(str[i]);
            for(j=0;j<len;j++)
            {
                strncpy(temp,str[i],j);
                if(h_search(temp)==1)
                {
                    printf("%s
    ",temp);
                    break;
                }
            }
            if(j==len) printf("%s
    ",str[i]);
        }
        del(head);
        return 0;
    }
  • 相关阅读:
    轻轻松松看懂Spring AOP源码
    centos7安装openjdk8
    使用fiddler做弱网测试
    测试术语-好东西要跟大家一块分享-2
    测试思想-好东西与大家分享-1
    session、token、cookie的区别
    接口测试和功能测试的区别
    常见bug解析-移动端
    接口测试的简介
    软件测试基本理论
  • 原文地址:https://www.cnblogs.com/dashuzhilin/p/4502547.html
Copyright © 2011-2022 走看看