首页 > 代码库 > Poj 2001 (Trie 前缀树)

Poj 2001 (Trie 前缀树)




#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#define MAXN 400010
#define MOD  20071027
#define INF  0x7fffffff
#define EPS  1e-8
#define PI acos(-1.0)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define bug(a) cout<<"bug---->"<<a<<endl;
#define FIN             freopen("datain.txt","r",stdin);
#define FOUT            freopen("dataout.txt","w",stdout);
#define mem(a,b)        memset(a,b,sizeof(a))
//#pragma comment         (linker,"/STACK:102400000,102400000")

typedef long long LL;
typedef unsigned long long ULL;
using namespace std;



struct Trie{
    int ch[200010][26];
    int time[200010];
    int sz;
    void clearr(){sz=1;memset(ch[0],0,sizeof ch[0]);memset(time,0,sizeof time);}
    int idx(char c){return c-'a';}
    void insertt(char *s);
    void findd(char *s);

};

void Trie::insertt(char *s)
{
    int u=0,v,i=0;
    while(s[i])
    {
        v=idx(s[i++]);
        if(!ch[u][v])
        {
            memset(ch[sz],0,sizeof ch[sz]);
            ch[u][v]=sz++;
        }
        u=ch[u][v];
        time[u]++;
    }
}

void Trie::findd(char *s)
{
    int u=0,v,i=0;
    while(s[i])
    {
        v=idx(s[i]);
        if(time[ch[u][v]]==1)
        {
            printf("%c",s[i]);
            return;
        }
        else
            printf("%c",s[i]);
        u=ch[u][v];
        i++;
    }
}


char s[10010][26];
Trie tree;

int main()
{
    tree.clearr();
    int n=0;
    while(scanf("%s",s[n])!=EOF) n++;
    for(int i=0;i<n;i++)
        tree.insertt(s[i]);
    for(int i=0;i<n;i++)
    {
        printf("%s ",s[i]);
        tree.findd(s[i]);
        printf("\n");
    }
    return 0;
}



Poj 2001 (Trie 前缀树)