字典树基础

#include<bits/stdc++.h>
using namespace std;
int trie[1000010][26]={0};
int sum[1000010]={0};
int pos=0;


void insert1( char *word )
{
    int root=0;
    for(int i=0;i<strlen(word);i++)
    {   int ch=word[i]-'a';
        if(trie[root][ ch ]==0)
            trie[root][ ch ]=++pos;
        root=trie[root][ch];
        sum[root]++;
    }
   


}


int find1(char *word)
{
    int root=0;
    for(int i=0;i<strlen(word);i++)
    {
        int ch=word[i]-'a';
        if(trie[root][ ch ]==0)return 0;
        root=trie[root][ch];

    }
    return sum[root];


}




int main()
{
    char word[15];
    while(gets(word))
    {
        if(strlen(word)==0)break;

        insert1(word);

    }
    while(gets(word))
    {
        printf("%d\n",find1(word));
    }


}

  

猜你喜欢

转载自www.cnblogs.com/bxd123/p/10342068.html