Problem Address:http://poj.org/problem?id=1816
【前言】
忽然看到文章说用指针占的空间比较大。
于是试了一下用int型的Trie。
感觉不用指针写的东西还是多了一点点。
【思路】
建树:
除了26个基本字符,应多加‘*’和‘?'。
如果单词末尾是‘*’,由于‘*’可以不代表字符,所以插入的时候需要特殊处理,对于‘*'前的字符串也应视为一个单词。
如果单词含有连续多个’*‘,则需处理为一个‘*’。
可能存在重复的模式串。
查询:
对于基本字符,基本查询。
同时需要查询‘?'。
还需要递归查询‘*’。
输出:
升序输出。
并注意重复id的情况。
此外,由于数据范围不好把握,空间上还是弄得蛮糟糕的。
【代码】
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100000;
struct node
{
int next[28];
int id[1000];
int pre;
int ct;
}trie[maxn];
int total;
int root;
int new_node(int father)
{
int p = total;
total++;
trie[p].ct = 0;
trie[p].pre = father;
int i;
for (i=0; i<28; i++)
trie[p].next[i] = -1;
return p;
}
void insert(int root, char *s, int index)
{
int i, t, p = root;
for (i=0; s[i]!='\0'; i++)
{
if (s[i]=='?') t = 26;
else if (s[i]=='*') t = 27;
else t = s[i]-'a';
if (trie[p].next[t]==-1)
trie[p].next[t] = new_node(p);
p = trie[p].next[t];
}
trie[p].id[trie[p].ct] = index;
trie[p].ct++;
if (s[i-1]=='*')
{
for (i=i-1; i>=0; i--)
{
if (s[i]=='*')
{
p = trie[p].pre;
trie[p].id[trie[p].ct] = index;
trie[p].ct++;
}
else break;
}
}
}
int num[maxn+5];
int ct;
void query(int root, char *s, int cur)
{
int i;
if (s[cur]=='\0')
{
for (i=0; i<trie[root].ct; i++)
{
num[ct] = trie[root].id[i];
ct++;
}
return;
}
int t = s[cur]-'a';
if (trie[root].next[t]!=-1)
query(trie[root].next[t], s, cur+1);
if (trie[root].next[26]!=-1)
query(trie[root].next[26], s, cur+1);
if (trie[root].next[27]!=-1)
{
for (i=cur; s[i]!='\0'; i++)
{
query(trie[root].next[27], s, i);
}
query(trie[root].next[27], s, i);
}
}
int main()
{
int n, m;
char str[30];
int i, j, k;
scanf("%d %d", &n, &m);
total = 0;
root = new_node(0);
for (i=0; i<n; i++)
{
scanf("%s", &str);
for (j=0, k=0; str[j]!='\0'; k++, j++)
{
str[k] = str[j];
if (str[j]=='*')
{
while(str[j+1]=='*' && str[j+1]!='\0')
j++;
}
}
str[k] = '\0';
insert(root, str, i);
}
for (i=0; i<m; i++)
{
scanf("%s", str);
ct = 0;
query(root, str, 0);
if (ct==0)
{
printf("Not match\n");
}
else
{
sort(num, num+ct);
printf("%d", num[0]);
for (j=1; j<ct; j++)
{
if (num[j]!=num[j-1])
{
printf(" %d", num[j]);
}
}
printf("\n");
}
}
return 0;
}