POJ2001Shortest Prefixes[Trie]

Shortest Prefixes
Time Limit: 1000MS   Memory Limit: 30000K
Total Submissions: 17683   Accepted: 7686

Description

A prefix of a string is a substring starting at the beginning of the given string. The prefixes of "carbon" are: "c", "ca", "car", "carb", "carbo", and "carbon". Note that the empty string is not considered a prefix in this problem, but every non-empty string is considered to be a prefix of itself. In everyday language, we tend to abbreviate words by prefixes. For example, "carbohydrate" is commonly abbreviated by "carb". In this problem, given a set of words, you will find for each word the shortest prefix that uniquely identifies the word it represents. 

In the sample input below, "carbohydrate" can be abbreviated to "carboh", but it cannot be abbreviated to "carbo" (or anything shorter) because there are other words in the list that begin with "carbo". 

An exact match will override a prefix match. For example, the prefix "car" matches the given word "car" exactly. Therefore, it is understood without ambiguity that "car" is an abbreviation for "car" , not for "carriage" or any of the other words in the list that begins with "car". 

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

Source


题意:给每个单词分一个最短前缀

裸的前缀树/字典树
val纪录这个节点经过几次,经过就++
查询时遇到val==1直接退出
愚蠢的给insert传了一个s[i]+1呵呵呵
//
//  main.cpp
//  poj2001
//
//  Created by Candy on 10/13/16.
//  Copyright © 2016 Candy. All rights reserved.
//

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
const int N=1e4+5;
int t[N*30][30],val[N*30],sz;
int n=0;
char s[N][30];
inline int id(char c){return c-'a';}
void insert(char a[]){
    int len=strlen(a+1),u=0;
    for(int i=1;i<=len;i++){
        int c=id(a[i]);
        if(!t[u][c]) t[u][c]=++sz;
        u=t[u][c];
        val[u]++;
    }
}
void query(char a[]){
    int len=strlen(a+1),u=0;
    for(int i=1;i<=len;i++){
        int c=id(a[i]);
        if(val[u]==1) break;
        putchar(a[i]);
        u=t[u][c];
    }
    putchar('\n');
}
int main(int argc, const char * argv[]) {
    while(scanf("%s",s[++n]+1)!=EOF) insert(s[n]);
    for(int i=1;i<=n;i++){
        printf("%s ",s[i]+1);
        query(s[i]);
    }
    return 0;
}

 

 
posted @ 2016-10-13 23:48  Candy?  阅读(214)  评论(0编辑  收藏  举报