• 最短的前缀


    Description
    现在人们喜欢用缩写,比如carbon可以缩写为carb,但不能缩写为car。因为有car这个准确的单词。给你n个单词(n<=1000),每个单词长度不超过20。求出每个单词的最短缩写。

    Input
    The input contains at least two, but no more than 1000 lines. Each line contains one word consisting of 1 to 20 lower case letters.
    Output
    The output contains the same number of lines as the input. Each line of the output contains the word from the corresponding line of the input, followed by one blank space, and the shortest prefix that uniquely (without ambiguity) identifies this word
    Sample Input
    carbohydrate
    cart
    carburetor
    caramel
    caribou
    carbonic
    cartilage
    carbon
    carriage
    carton
    car
    carbonate
    Sample Output
    carbohydrate carboh
    cart cart
    carburetor carbu
    caramel cara
    caribou cari
    carbonic carboni
    cartilage carti
    carbon carbon
    carriage carr
    carton carto
    car car
    carbonate carbona

    sol:比较简单,建Trie,记录下每个结点经过的次数。找每个单词的缩写时,从根出发,依次看当前结点被经过的次数,如果当前字符被经过的次数不止一次,说明当前找出来的缩写还是别的单词的前缀,继续找,直到找到某字符只被经历了一遍。当然整个单词都有可能是别的单词的前缀。

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cmath>
     4 #include<cstring>
     5 #include<algorithm>
     6 using namespace std;
     7 const int chnum=26;
     8 struct NODE{
     9     int ct;//该节点被使用的次数
    10     short a[26];//子节点
    11 }n[15000];
    12 int cnt;//总节点数
    13 char c[2000][25];
    14 void ins(char s[])
    15 {
    16     int num=0,len=strlen(s);
    17     int i,j;
    18     for(i=0;i<len;i++)
    19     {
    20         if(n[num].a[s[i]-'a']==0)
    21         {
    22             cnt++;//增加节点 
    23             n[num].a[s[i]-'a']=cnt;
    24             num=cnt;
    25         }
    26         else num=n[num].a[s[i]-'a'];//用已有结点         
    27         n[num].ct++;//该节点使用次数+1
    28     }
    29     return;
    30 }
    31 void Print(char s[])
    32 {
    33     int num=0,len=strlen(s);
    34     printf("%s ",s);
    35     for(int i=0;i<len;i++)
    36     {
    37         num=n[num].a[s[i]-'a'];
    38         printf("%c",s[i]);
    39         if(n[num].ct==1) 
    40         {
    41         //printf("
    ");//由于有些词是被完全包含在其他词里的,故不能在这里换行
    42         break;
    43         }
    44     }
    45     printf("
    ");
    46     return;
    47 }
    48 int main()
    49 {
    50     int i=0,j;
    51     while(cin>>c[i] && c[i]!='')ins(c[i++]);
    52     for(j=0;j<i;j++)Print(c[j]);
    53     return 0;
    54 }
  • 相关阅读:
    字节序(Endian),大端(BigEndian),小端(LittleEndian)
    关于PHOTO SHOP CS9.0无法启动adobe updater 请重新安装应用程序和组件解决方法!
    工作·事业·人生
    多选列表Select之双击删除与添加Demo
    WIN7任务栏修复解决windows7任务栏不能停靠图标的问题
    ip地址被绑定,vmware无法共享上网,
    小屋·小篮子·祭
    基础知识提问:关于HashTable和List两个容器Add改变了属性的同一对象的问题
    [转载]正则表达式30分钟入门教程及MTracer(破解版)
    让程序更健壮,用错误还是抛异常?
  • 原文地址:https://www.cnblogs.com/cutepota/p/12614442.html
Copyright © 2020-2023  润新知