POJ 2001 Shortest Prefixes (字典树 TRIE)

题目链接:http://poj.org/problem?id=2001


【题目大意】

给你一些单词,让你求出他们最短的前缀,当然,这个前缀不能有歧义,例如给出单词 carton cart car

carton的 前缀 就不能是cart,因为cart的前缀是cart,同理cart的前缀也不能是car。

要找到每个单词独一无二且是最短的前缀,car的前缀不能是,”c“  “ca” ,因为他们在别的单词中也有出现,

如果找不到独一无二,那个这个单词本身就是他自己的前缀。


【样例输入】

carbohydrate
cart
carburetor
caramel
caribou
carbonic
cartilage
carbon
carriage
carton
car
carbonate

【样例输出】

carbohydrate carboh
cart cart
carburetor carbu
caramel cara
caribou cari
carbonic carboni
cartilage carti
carbon carbon
carriage carr
carton carto
car car
carbonate carbona


【思路】

将单词全部存入字典树

修改字典树的查找函数

void search(string s){
	int len =s.length();
	node *a=root;
	string ans=""; //记录prefixes
	for(int i=0;i<len;i++){
 		int k=s[i]-'a';
		 ans+=s[i];
		a=a->next[k];
		if(a->v==1){ //如果前缀唯一
			cout<<s<<" "<<ans<<endl;return ;
 		}
		if(a==NULL) return ;
	}
	cout<<s<<" "<<s<<endl; //否则输出本身
	// return a->v;
}

【源代码】

#include <iostream>
#include <cstdio>
#include <set>
#include <map>
#include <algorithm>
#include <cstring>
#include <string>
const int maxn = 1010;
using namespace std;
string Map[1010];
struct node{
    int v;
    node* next[26];
    node(){
        v=0;
        memset(next,0,sizeof(next));
    }
}*root;
void add(string word){
    int len=word.length();
    node*a=root,*b;
    for(int i=0;i<len;i++){
        int k=word[i]-'a';
        if(a->next[k]!=NULL){
            a=a->next[k];
            a->v++;
        }
        else{
            // cout<<"bug "<<endl;
            b=new node;
            b->v=1;
            a->next[k]=b;
            a=a->next[k];
        }
    }
}
void search(string s){
    int len =s.length();
    node *a=root;
    string ans="";
    for(int i=0;i<len;i++){
        int k=s[i]-'a';
        ans+=s[i];
        a=a->next[k];
        if(a->v==1){
            cout<<s<<" "<<ans<<endl;return ;
        }
        if(a==NULL) return ;
    }
    cout<<s<<" "<<s<<endl;
    // return a->v;
}
void clear(node *a){
    if(a==NULL)
        return ;
    else{
        for(int i=0;i<26;i++){
            clear(a->next[i]);
        }
    }
    delete(a);
}
int main(){
    string tmp;
    int cnt=0;
    root = new node;
    while(cin>>tmp){
        add(tmp);
        Map[cnt++]=tmp;
    }
    for(int i=0;i<cnt;i++){
        search(Map[i]);
    }
    clear(root);
    return 0;
}

另外本人写的暴力加排序代码也过了,分析后才知是后台数据水的缘故,还是要多多思考再敲代码。


转载于:https://www.cnblogs.com/chaiwenjun000/p/5321186.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值