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 }
  • 相关阅读:
    应用开发框架之——业务规则脚本化
    tms脚本演示代码之一
    根据.DFM文件动态生成窗体以及在之前先必须注册窗体中使用到的类
    界面/业务规则脚本化
    delphi 脚本引擎比较
    html5 datalist 选中option选项后的触发事件
    Laravel 5.6 模型关联 user 表后查询 user 表数据只能获取第一条数据,不知道怎么获取第二条...
    小技巧两个感叹号(两个!)连用
    Bootstrap 字体图标(Glyphicons)
    使用withCount后再使用select设置查询的字段。就找不到withCount的数据了
  • 原文地址:https://www.cnblogs.com/cutepota/p/12614442.html
Copyright © 2011-2022 走看看