[Tyvj1228 有道搜索框]

[题目来源]:tyvj1128

[关键字]:字典树

[题目大意]:给出一个字典。接着输入字符串s查询最多前8个依次为前缀的字典中的单词,如没有只输出s。

//============================================================================================================

[分析]:用字典树,首先将每个单词插入字典树,然后寻找到s插入字典树后在字典树中的节点,以此为起点进行dfs,如果s无法插入树中说明没有依次为前缀得单词。

[代码]:

View Code
 1 program Project1;
2 type
3 rec = record
4 dat: array['a'..'z'] of longint;
5 f: boolean;
6 s: string;
7 end;
8 var
9 tot, tn, n, q: longint;
10 tree: array[0..2000000] of rec;
11
12 procedure inser(s: string);
13 var
14 i, now: longint;
15 begin
16 now := 1;
17 for i := 1 to length(s) do
18 if tree[now].dat[s[i]] <> 0 then now := tree[now].dat[s[i]]
19 else
20 begin
21 inc(tn);
22 tree[tn].f := false;
23 tree[now].dat[s[i]] := tn;
24 now := tn;
25 end;
26 tree[now].s := s;
27 tree[now].f := true;
28 end;
29
30 procedure dfs(k: longint);
31 var
32 ch: char;
33 begin
34 if tree[k].f then
35 begin
36 inc(tot);
37 write(tree[k].s,'');
38 end;
39 for ch := 'a' to 'z' do
40 begin
41 if tree[k].dat[ch] <> 0 then dfs(tree[k].dat[ch]);
42 if tot = 8 then exit;
43 end;
44 end;
45
46 procedure find(s: string);
47 var
48 now, i: longint;
49 begin
50 now := 1;
51 for i := 1 to length(s) do
52 if tree[now].dat[s[i]] <> 0 then now := tree[now].dat[s[i]]
53 else exit;
54 dfs(now);
55 end;
56
57 procedure init;
58 var
59 i: longint;
60 s: string;
61 begin
62 readln(n);
63 tn := 1;
64 for i := 1 to n do
65 begin
66 readln(s);
67 inser(s);
68 end;
69 readln(q);
70 for i := 1 to q do
71 begin
72 readln(s);
73 tot := 0;
74 find(s);
75 if tot = 0 then writeln(s) else writeln;
76 end;
77 end;
78
79 begin
80 //assign(input,'c:\1.in');reset(input);
81 assign(output,'c:\1.out');rewrite(output);
82 init;
83 close(input);
84 close(output);
85 end.

 

你可能感兴趣的:(搜索)