Problem Descriptionignatius recently encountered a problem, the teacher gave him a lot of words (only lowercase letters, no duplicate words appear), now the teacher asked him to count the number of words prefixed with a string (the word itself is also its own prefix). The first part of input data is a Word table, one word per line, the length of the word is not more than 10, they represent the word that the teacher handed to Ignatius, and a blank line represents the end of the Word table. The second part is a series of questions, one question per line, and each question is a string.
Note: There is only one set of test data, processing to the end of the file. Output for each question, give the number of words prefixed with the string. Sample INPUTBANANABANDBEEABSOLUTEACM Babbandabc Sample Output2310 Parse: Add 1 to each position in the process of inserting the dictionary tree. Code#include <cstdio>
#include <cstring>
Const
intMaxn
=500005
;
struct Tree
{
int Next
[ -
];
int Info
;
void Init
(){Memset
(Next
,-1
,
sizeof
(Next
));Info
=0
; }
}Tree
[Maxn
];
int Id
;
int GetIndex
(
CharC
){
returnC
-' A '
; }
void Init
(){
for
(
intI
=0
;I
<Maxn
;I
++)Tree
[I
].Init
();Id
=0
; }
void Insert
(
CharS
[])
{
int Be
=0
;
int Je
=Strlen
(S
);
for
(
intI
=0
;I
<Je
;I
++)
{
int S
=GetIndex
(S
[I
]);
Tree
&T
=Tree
[Be
];
If
(T
.Next
[S
]==-1
)T
.Next
[S
]=++Id
;
Be
=T
.Next
[S
];
Tree
[Be
].Info
++; Plus 1
}
}
int Search
(
CharS
[])
{
int Len
=Strlen
(S
);
int Be
=0
;
for
(
intI
=0
;I
<Len
;I
++)
{
int S
=GetIndex
(S
[I
]);
Tree
&T
=Tree
[Be
];
If
(T
.Next
[S
]==-1
)
return0
; Not found
Be
=T
.Next
[S
];
}
return Tree
[Be
].Info
; Number of returns
}
int
Main
()
{
Init
();
Char Word
[ One
];
while
(Gets
(Word
))
{
If
(Word
[0
]==' + '
)
Break
;
Insert
(Word
);
}
while
(Gets
(Word
)!=Null
)
{
Printf
("%d\n"
,Search
(Word
));
}
return 0
;
}
hdu1251-Statistical Puzzles (dictionary tree)