字典树——POJ2001

题目链接

从没遇到过这样的题,居然不给字符串的个数

输出前缀的方法也没见过

就是string一个空字符串,然后用string类的加法

思路倒是很简单,建字典树,每一个字符串的每一个字符sum++

如果sum==1说明这个字符只有你经过,没有和其他字符串重叠,那就可以

题目代码

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<sstream>
using namespace std;
const int maxn=2e4+7;
char str[1007][30];
int cnt,tot,sum[maxn],tree[maxn][30];
void insert(char *s){
    int len=strlen(s);
    int root=0;
    for(int i=0;i<len;i++){
        int id=s[i]-'a';
        if(!tree[root][id])tree[root][id]=++tot;
        sum[tree[root][id]]++;
        root=tree[root][id];
    }
}
string find(char *s){
    string ans="";
    int len=strlen(s);
    int root=0;
    for(int i=0;i<len;i++){
        int id=s[i]-'a';
        ans+=s[i];
        root=tree[root][id];
        if(sum[root]==1)return ans;
    }
    return ans;
}
int main(){
    while(scanf("%s",&str[cnt])!=EOF){
        insert(str[cnt]);
        cnt++;
    }
    for(int i=0;i<cnt;i++){
        string ans=find(str[i]);
        printf("%s %s
",str[i],ans.c_str());
    }
    return 0;
}
原文地址:https://www.cnblogs.com/helman/p/11304038.html