博客
关于我
Shortest Prefixes(trie树唯一标识)
阅读量:621 次
发布时间:2019-03-13

本文共 1270 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要找到每个给定单词的最短前缀,这个前缀必须唯一地标识该单词。也就是说,这个前缀应该是这个单词的最短开始部分,使得没有其他单词在输入集中以这个前缀开始。

方法思路

  • 读取输入:首先,我们读取所有输入的单词,并将它们存储在一个列表中。
  • 构建前缀哈希表:使用一个字典来记录每个前缀及其对应的单词数量。键是前缀,值是一个列表,包含所有以该前缀开头的单词。
  • 处理每个单词:对于每个单词,生成其所有可能的前缀,从最长到最短(即从长度为n到1)。检查每个前缀是否在哈希表中对应的单词数量为1。如果满足条件,那么这个前缀就是该单词的最短前缀。
  • 解决代码

    import sysfrom collections import defaultdictdef main():    words = []    for line in sys.stdin:        line = line.strip()        if line:            words.append(line)        # Build prefix map    prefix_map = defaultdict(list)    for word in words:        for i in range(len(word)):            prefix = word[:i+1]            prefix_map[prefix].append(word)        # Process each word to find the minimal prefix    for word in words:        found = False        for i in range(len(word)-1, -1, -1):            prefix = word[:i+1]            if len(prefix_map[prefix]) == 1:                print(f"{word} {prefix}")                found = True                break        if not found:            print(f"{word} {word}")if __name__ == "__main__":    main()

    代码解释

  • 读取输入:使用sys.stdin读取输入,并将每行非空字符串添加到words列表中。
  • 构建前缀哈希表:遍历每个单词,生成其所有可能的前缀,并将这些前缀及其对应的单词添加到prefix_map字典中。
  • 处理每个单词:对于每个单词,生成其所有可能的前缀,按从长到短的顺序检查每个前缀。如果找到一个前缀在哈希表中对应的单词数量为1,则输出该前缀。否则,输出整个单词本身作为前缀。
  • 这种方法确保了我们能够高效地找到每个单词的最短前缀,并且保证了这个前缀的唯一性。

    转载地址:http://nueaz.baihongyu.com/

    你可能感兴趣的文章
    POJ 2403
    查看>>
    poj 2406 还是KMP的简单应用
    查看>>
    POJ 2431 Expedition 优先队列
    查看>>
    Qt笔记——获取位置信息的相关函数
    查看>>
    POJ 2484 A Funny Game(神题!)
    查看>>
    POJ 2486 树形dp
    查看>>
    POJ 2488:A Knight's Journey
    查看>>
    SpringBoot为什么易学难精?
    查看>>
    poj 2545 Hamming Problem
    查看>>
    poj 2723
    查看>>
    poj 2763 Housewife Wind
    查看>>
    Qt笔记——模型/视图MVD 文件目录浏览器软件
    查看>>
    POJ 2892 Tunnel Warfare(树状数组+二分)
    查看>>
    poj 2965 The Pilots Brothers' refrigerator-1
    查看>>
    poj 3026( Borg Maze BFS + Prim)
    查看>>
    POJ 3041 - 最大二分匹配
    查看>>
    POJ 3041 Asteroids(二分匹配模板题)
    查看>>
    Qt笔记——标准文件对话框QFileDialog
    查看>>
    poj 3083 Children of the Candy Corn
    查看>>
    POJ 3083 Children of the Candy Corn 解题报告
    查看>>