HUD 1251 难题统计

本文探讨了字典树在空间使用上的优化方法,通过采用map替代数组来减少内存消耗,并对比了两种实现方式的空间效率。同时介绍了如何利用指针动态分配内存进一步优化空间使用。
/*
这题倒是没啥难度 字典树可搞
但是吧 空间是个问题 
 开始写成这样 
 struct node
{
    int next[27],sum[27];
    bool over;
}t[maxn]; 
死活过不了 开小了er 开大了MLE
问了问wmy 很机智的说用map 管用的 然后卡空间过了
看他们用指针动态分配内存 然而我并不太会..... 
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#define maxn 480010
using namespace std;
int topt;
char s[20];
struct node
{
    map<int,int>next,sum;
    bool over;
}t[maxn];
void Add_tree()
{
    int now=0,l=strlen(s);
    for(int i=0;i<l;i++)
      {
          int x=s[i]-'a'+1;
          if(t[now].next[x])
            {
                t[now].sum[x]++;
                now=t[now].next[x];
          }
        else 
          {
              topt++;t[now].next[x]=topt;
              t[now].sum[x]++;now=topt;
          }
      }
}
int find_tree()
{
    int ans=0,p=0,now=0,l=strlen(s),x,pre;
    while(p<=l-1)
      {
          x=s[p]-'a'+1;
          if(t[now].next[x])pre=now,now=t[now].next[x],p++;
          else return 0;
      }
    return t[pre].sum[x];
}
int main()
{
    while(gets(s)&&strlen(s))Add_tree();
    while(gets(s))cout<<find_tree()<<endl;
    return 0;
}

 

/*
    恩 之前一直纠结空间
    因为状态写错了 可以不用那么多.... 
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<map>
#define maxn 500010
using namespace std;
int topt;
char s[20];
struct node
{
    int next[27],sum;
}t[maxn];
void Add_tree()
{
    int now=0,l=strlen(s);
    for(int i=0;i<l;i++)
      {
          int x=s[i]-'a'+1;
          if(t[now].next[x])now=t[now].next[x];
        else 
          {
              topt++;t[now].next[x]=topt;now=topt;
          }
        t[now].sum++;
      }
}
int find_tree()
{
    int ans=0,p=0,now=0,l=strlen(s);
    while(p<=l-1)
      {
          int x=s[p]-'a'+1;
          if(t[now].next[x])now=t[now].next[x],p++;
          else return 0;
      }
    return t[now].sum;
}
int main()
{
    while(gets(s)&&strlen(s))Add_tree();
    while(gets(s))cout<<find_tree()<<endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/yanlifneg/p/5659491.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值