建树:
二维数组模拟
void add(char str[10])
{
ll len = strlen(str),to = 1; //to表示下一个节点
for(ll i = 0; i < len; i++)
{
ll t = str[i]-'a';
if(tire[to][t] == 0)
{
cnt++; //最大节点数
tire[to][t] = cnt;
}
to = tire[to][t];
}
end[to] = true; //end函数来标记当前单词是否结束了
return ;
}
查询:
习题: http://codevs.cn/problem/4189/
bool query(char str[10])
{
ll len = strlen(str),to = 1;
for(ll i = 0; i < len; i++)
{
if( tire[to][ str[i]-'a' ] == 0) //如果没这个字符直接结束
return false;
to = tire[to][ str[i]-'a' ];
}
return true;
//return end[to]; //查前缀的话就不能用这句了,建树中单词的字串是没有记录结束的
}
查询当前单词是字典树中多少单词的前缀
习题:http://acm.hdu.edu.cn/showproblem.php?pid=1251
void add(char str[15])
{
ll len = strlen(str),to = 1;
for(ll i = 0; i < len; i++)
{
ll t = str[i]-'a';
if(tire[to][t] == 0)
{
cnt++;
tire[to][t] = cnt;
}
to = tire[to][t];
sum[to]++; //在建树中 开个数组标记一下当前位置的前缀数
}
strend[to] = true;
return ;
}
查询树中有多少单词是当前字符的前缀
习题:http://acm.ncst.edu.cn/problem.php?pid=1421
void add(char str[])
{
ll to = 1,len = strlen(str);
for(ll i = 0; i < len; i++)
{
ll t = str[i]-'a';
if(tire[to][t] == 0)
{
//strend[to]++;
cnt++;
tire[to][t] = cnt;
}
to = tire[to][t];
}
strend[to]++; //以当前字符结尾的单词有多少个
return ;
}
ll query(char str[])
{
ll to = 1,len = strlen(str),ans = 0;
for(ll i = 0; i < len; i++)
{
if(tire[to][str[i]-'a'] == 0) //先判断
break;
to = tire[to][ str[i]-'a' ];
ans += strend[to];
}
return ans;
}