POJ 2001 Shortest Prefixes

本文介绍了一种使用字典树解决POJ2001问题的方法。通过构建字典树来存储一系列字符串,并能快速查找每个字符串在树中是否唯一。文章提供了完整的C++代码实现。

传送门:http://poj.org/problem?id=2001

解题思路:

简单的字典树

实现代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
using namespace std;

const int N=27;
struct node{
    int cnt;
    node *childs[N];
    node(){
        cnt=0;
        for(int i=0;i<N;i++)
            childs[i]=NULL;
    }
};

node *root=new node;
node *current,*newnode;

void insert(char *str){
    int n=strlen(str);
    current=root;
    for(int i=0;i<n;i++){
        int m=str[i]-'a';
        if(current->childs[m]!=NULL){
            current=current->childs[m];
            (current->cnt)++;
        }else{
            newnode=new node;
            (newnode->cnt)++;
            current->childs[m]=newnode;
            current=newnode;
        }
    }

}

void search(char *str){
    int n=strlen(str);
    current=root;
    for(int i=0;i<n;i++){
        int m=str[i]-'a';
        if(current->cnt==1){
            printf("\n");
            return;
        }else{
            printf("%c",str[i]);
        }
        current=current->childs[m];
    }
    printf("\n");
}

int main(){
    char a[5000][300];

    int n=0;
    while(scanf("%s",a[n])!=EOF){
        insert(a[n]);
        n++;
    }
    for(int i=0;i<n;i++){
        printf("%s ",a[i]);
        search(a[i]);
    }

}

 

转载于:https://www.cnblogs.com/IKnowYou0/p/6657226.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值