zoukankan      html  css  js  c++  java
  • 最短的前缀

    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 }
  • 相关阅读:
    (二)juc线程高级特性——CountDownLatch / Callable / Lock
    (一)juc线程高级特性——volatile / CAS算法 / ConcurrentHashMap
    配置tomcat的session共享
    elastic不错的官方文档(中文)
    elasticsearch java客户端api使用(一)
    Tomcat 没有自动解压webapp下的war项目文件问题
    Spring+Quartz实现定时任务
    注意的问题
    JMS之——ActiveMQ 高可用与负载均衡集群安装、配置(ZooKeeper + LevelDB + Static discovery)
    activemq持久化配置,设置为主从模式(带复制的主从模式,应用mysql数据库)
  • 原文地址:https://www.cnblogs.com/cutepota/p/12614442.html
Copyright © 2011-2022 走看看