zoukankan      html  css  js  c++  java
  • poj 2001 Shortest Prefixes

      字典树的简单应用。

      

    #include<stdio.h>
    #include<string.h>
    
    char str[10100][22];
    struct node{
        int cnt;
        node *next[26];
    }*p;
    void build(char str[],int k,node *head)
    {
        while(k<strlen(str))
        {
            if(head->next[str[k]-'a']!=NULL)
            {
                head->next[str[k]-'a']->cnt+=1;
                head=head->next[str[k]-'a'];
            }
            else
            {
                head->next[str[k]-'a']=new node;
                head=head->next[str[k]-'a'];
                head->cnt=1;
                for(int i=0;i<26;i++)
                    head->next[i]=NULL;
            }
            k++;
        }
    }
    void search(char str[],int k,node *head)
    {
        while(k<strlen(str))
        {
            if(head->next[str[k]-'a']!=NULL)
            {
                printf("%c",str[k]);
                if(head->next[str[k]-'a']->cnt==1)
                    return ;
            }
            head=head->next[str[k]-'a'];
            k++;
        }
    }
    void del(node *head)
    {
        if(head==NULL)
            return ;
        for(int i=0;i<26;i++)
        {
            del(head->next[i]);
            head->next[i]=NULL;
        }
        delete(head);
    }
    int main()
    {
        p=new node;
        for(int i=0;i<26;i++)
            p->next[i]=NULL;
        int cnt=0;
        while(~scanf("%s",str[cnt]))
        {
            build(str[cnt],0,p);
            cnt++;
        }
        for(int i=0;i<cnt;i++)
        {
            printf("%s ",str[i]);
            search(str[i],0,p);
            printf("
    ");
        }
        del(p);
        return 0;
    }
  • 相关阅读:
    54.施工方案第二季(最小生成树)
    53.FIB词链
    53.FIB词链
    53.FIB词链
    52.1076 排序
    52.1076 排序
    52.1076 排序
    52.1076 排序
    upc-9541 矩阵乘法 (矩阵分块)
    记录deepin设置自动代理
  • 原文地址:https://www.cnblogs.com/yongren1zu/p/3278589.html
Copyright © 2011-2022 走看看