• poj 2001 Shortest Prefixes Trie树


    题意:输入n个字符串,求每个字符串的最短非公共前缀,若没有输出其本身

    思路:Trie水题

     1 #include<iostream>
    2 using namespace std;
    3 #define MAXL 21
    4 #define MAXN 1001
    5 struct node
    6 {
    7 int count;
    8 node *next[30];
    9 };
    10 int n=0;
    11 node *root;
    12 int top=0;
    13 int end_node;
    14 node memo[MAXN*MAXL];
    15 void insert(char c[])
    16 {
    17 int i;
    18 int l=strlen(c);
    19 node *t=root;
    20 for(i=0;i<l;i++)
    21 {
    22 int x=c[i]-'a';
    23 if(t->next[x]==NULL)
    24 {
    25 node *p=&memo[top++]; t->next[x]=p;
    26 }
    27 t=t->next[x];
    28 t->count++;
    29 }
    30 }
    31 void search(char c[])
    32 {
    33 int i;
    34 end_node=-1;
    35 int m=strlen(c);
    36 node *p=root;
    37 for(i=0;i<=m-1;i++)
    38 {
    39 p=p->next[c[i]-'a'];
    40 if(p->count>1) end_node=i;
    41 }
    42 if(end_node==m-1) end_node=m-2;
    43 for(i=0;i<=end_node+1;i++)printf("%c",c[i]);
    44 printf("\n");
    45 }
    46 char c[MAXN][MAXL];
    47 int main()
    48 {
    49 int i;
    50 memset(memo,0,sizeof(memo));
    51 top=0; root=&memo[top++];
    52 while(scanf("%s",c[++n])!=EOF) insert(c[n]);
    53 for(i=1;i<n;i++)
    54 {
    55 printf("%s ",c[i]);
    56 search(c[i]);
    57 }
    58 //system("pause");
    59 return 0;
    60 }
  • 相关阅读:
    FullCalendar日历插件说明文档
    Git忽略规则及.gitignore规则不生效的解决办法
    学习git config配置文件
    拼接最长回文串
    Gildong owns a bulgogi restaurant
    前m大的数
    求水洼(dfs)
    循环数组的最大子段和
    求叶子节点
    周期
  • 原文地址:https://www.cnblogs.com/myoi/p/2345904.html
Copyright © 2020-2023  润新知