【字典树_前缀出现次数】HDU 1251 统计难题

字典树

tire[ rt ][ i ] = k : 结点 rt 下的子结点 k 值为 i

HDU 1251 统计难题

字典树模板题
【注意】

  1. 字符串的输入处理
  2. 数组大小的开辟
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <list>
#include <map>
#define INF 0x3f3f3f3f
#define P(x) x>0 ? x : 0
#define MID l + r >> 1
#define lsn rt << 1
#define rsn rt << 1 | 1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr

using namespace std;
typedef long long ll;
typedef vector<int>:: iterator VITer;
const int maxN=5e5+5;
char s[15],qs[15];
int tire[maxN][26],sum[maxN],rt,tot;

void init()
{
    memset(tire, 0, sizeof(tire));
    memset(sum, 0, sizeof(sum));
    tot=0;
}

void Insert()
{
    int len=strlen(s);
    rt=0;
    for(int i = 0; i < len; i ++ )
    {
        int id=s[i]-'a';
        if(!tire[rt][id]) tire[rt][id] = ++tot;//rt结点没有id的子节点
        sum[tire[rt][id]]++;
        rt=tire[rt][id];
    }
}

int Search()
{
    int len=strlen(qs);
    rt=0;
    for(int i = 0; i < len ; i ++ )
    {
        int id=qs[i]-'a';
        if(!tire[rt][id]) return 0;
        rt=tire[rt][id];
    }
    return sum[rt];
}

int main()
{
    init();
    while( gets(s) && strlen(s))
    {
        Insert();
    }
    while( gets(qs) && strlen(qs))
    {
        printf("%d\n", Search());
    }
    return 0;
}

字典树讲解

…………………………………………………………………………………

最近在复习……都忘记了

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxN = 2000000 + 7;
int tire[maxN][26], tot;
int sum[maxN];
void Insert(char *s)
{
    int len = strlen(s);
    int rt = 0;
    for(int i = 0; i < len; i ++ )
    {
        int id = s[i] - 'a';
        if(!tire[rt][id]) tire[rt][id] = ++ tot;
        ++ sum[tire[rt][id]];
        rt = tire[rt][id];
    }
}
int Search(char *s)
{
    int len = strlen(s);
    int rt = 0;
    for(int i = 0; i < len; i ++ )
    {
        int id = s[i] - 'a';
        if(!tire[rt][id]) return 0;//没有继续往下的必要了,因为已经没有了
        rt = tire[rt][id];
    }
    return sum[rt];
}
int main()
{
    char s[15];
    while(gets(s) && s[0] != '\0')
        Insert(s);
    while(~scanf("%s", s))
        printf("%d\n", Search(s));
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值