UVA 11732 strcmp() Anyone 左兄弟右孩子Trie

来源:互联网 发布:3季度经济数据 编辑:程序博客网 时间:2024/06/04 17:46
/*因为比较函数如上,计算时要注意以下几点:            1.相同长度为L的两个单词比较代价为2L-1,出最后一次外要进行s结束的判断;            2.单词的比较长度应该为strlen(str)+1,结束符也是比较的一环;            3.如果两个单词相同,则多计算一次结束判断,比较次数+1。*/#include <iostream>#include <cstring>#include <queue>#include <stdlib.h>#include <stdio.h>using namespace std;const int MAX=4567890;char words[1010];struct node{    char value;    int size;    int count;    node* leftchild;    node* rightchild;};//左兄弟,右孩子node dict[MAX];struct trie{    long long count;    int size;    node* root;    trie()    {        init();    }    void init()    {        memset(dict,0,sizeof(dict));        size=0;        count=0LL;        root=newnode(0);    }    node* newnode(char c)    {        dict[size].value=c;        return &dict[size++];    }    void insert(char* word,int L)    {        node* now=root->rightchild,*save=root;        int same=1;        for (int i=0;i<=L;i++)        {            if (!now)            {                save->rightchild=newnode(word[i]);                now=save->rightchild;                now->count=1;                same=0;            }            else            {                if (i)                    count+=now->count;                count+=now->count++;                while (now->leftchild&&now->value!=word[i])                    now=now->leftchild;                if (now->value!=word[i])                {                    now->leftchild=newnode(word[i]);                    now=now->leftchild;                    same=0;                }            }            save=now;            now=save->rightchild;        }        if (same)            save->size++;        count+=save->size;    }    long long query()    {        return count;    }};trie t;int main(){    int Case=1,N;    while (scanf("%d",&N)!=EOF)    {        if (!N)            break;        t.init();        for (int i=0;i<N;i++)        {            scanf("%s",words);            t.insert(words,strlen(words));        }        printf("Case %d: %lld\n",Case++,t.query());    }    return 0;}
0 0
原创粉丝点击