百度之星 预赛004--字典树

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

struct node {
    int cnt;//记录个数;
    struct node *next[26];
    node()
    {
        cnt=0;
        memset(next,NULL,sizeof(next));
    }
};

void buildtrie(node *root,string s)//建树;
{
    node *p=root;
    node *tmp=NULL;
    int l=s.size();
    for(int i=0;i<l;i++)
    {
        if(p->next[s[i]-'A']==NULL)
        {
            tmp=new node;
            p->next[s[i]-'A']=tmp;
        }
        p=p->next[s[i]-'A'];
    }
    p->cnt++;
}

void findtrie(node *root ,string s)//查询
{
    node *p=root;
    int l=s.size();
    for(int i=0;i<l;i++)
    {
        p=p->next[s[i]-'A'];
    }
    printf("%d
",p->cnt-1);
}
/*
void del(node *root)
{
    for(int i=0;i<10;i++)
        if(root->next[i])
            del(root->next[i]);
    delete(root);
}
*/
int main()
{
    int n;
    string s;
    node root;
    scanf("%d",&n);
    while(n--)
    {
        cin >> s;
        sort(s.begin(),s.end());
        buildtrie(&root,s);
        findtrie(&root,s);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/WDKER/p/5495010.html