字典树简单应用

题目链接:http://acdream.info/problem?pid=1121
题意:在cashe中有一些单词,通过题目中的三个操作,求得到给定单词的最少操作数。

 很明显用字典树来解,最少操作数 = min(给定单词长度 - 已经走的路程 + 里最近叶子节点的距离)

代码如下:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<time.h>
#include<math.h>

#define  N 1000000 + 5
#define inf 0x7fffffff
#define eps 1e-9
#define pi acos(-1.0)
#define P system("pause")
using namespace std;
char str[N];
int res ;
struct trie
{
    int ch[N/10][30];
    int val[N/10];//记录到最近的叶子节点的距离
    int sz;
    trie()
    {
        memset(ch[0],0,sizeof(ch[0]));
        sz = 1;
    }

    void insert()
    {
        int len = strlen(str);
        int i, u = 0;
        for(i = 0; i < len; i++)
        {
            int c = str[i] - 'a';
            if(!ch[u][c])
            {
                memset(ch[sz],0,sizeof(ch[sz]));
                ch[u][c] = sz++;
                val[ch[u][c]] = len - i - 1;
            }
            else
                val[ch[u][c]] = min(val[ch[u][c]], len - i - 1);
            u = ch[u][c];
        }
        val[u] = 0;
    }
    void query()
    {
        int len = strlen(str);
        int i, u = 0;
        for(i = 0; i < len; i++)
        {
            int c = str[i] - 'a';
            if(!ch[u][c])
                break;
            u = ch[u][c];
            res = min(res,len - i + val[u]);
        }
    }
};
trie tree;
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int n;
        memset(tree.val,0,sizeof(tree.val));
        memset(tree.ch,0,sizeof(tree.ch));
        sz = 1;
        scanf("%d",&n);
        scanf("%s",str);
        tree.insert();
        while(n--)
        {
            scanf("%s",str);
            res = strlen(str);
            tree.query();
            printf("%d\n",res);
            tree.insert();
        }
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值