字典树
tire[ rt ][ i ] = k : 结点 rt 下的子结点 k 值为 i
字典树模板题
【注意】
- 字符串的输入处理
- 数组大小的开辟
#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;
}