Problem Description Problem Analysis This is a Trie template problem: record a cnt for each node The cnt of the last letter is the number of words prefixed by s Remember to free the memory HDU’s G++ keeps running out of memory……C++ can get AC
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct Trie {
int cnt ;
Trie * next [ 26 ];
} * root ;
void Insert ( char * s ) {
Trie * p , * t ;
int l = strlen ( s );
p = root ;
for ( int i = 0 ; i < l ; i ++ ) {
if ( p -> next [ s [ i ] - 'a' ] == NULL ) {
t = new Trie ;
t -> cnt = 1 ;
for ( int j = 0 ; j < 26 ; j ++ )
t -> next [ j ] = NULL ;
p -> next [ s [ i ] - 'a' ] = t ;
} else
p -> next [ s [ i ] - 'a' ] -> cnt ++ ;
p = p -> next [ s [ i ] - 'a' ];
}
}
int Search ( char * s ) {
Trie * p ;
int l = strlen ( s );
p = root ;
for ( int i = 0 ; i < l ; i ++ ) {
if ( p -> next [ s [ i ] - 'a' ] == NULL )
return 0 ;
p = p -> next [ s [ i ] - 'a' ];
}
return p -> cnt ;
}
void Release ( Trie * p ) {
if ( p == NULL )
return ;
for ( int i = 0 ; i < 26 ; i ++ )
if ( p -> next [ i ] != NULL )
Release ( p -> next [ i ]);
free ( p );
root = NULL ;
return ;
}
void Init () {
root = new Trie ;
root -> cnt = 0 ;
for ( int i = 0 ; i < 26 ; i ++ )
root -> next [ i ] = NULL ;
}
int main () {
char str [ 15 ];
Init ();
while ( gets ( str ), strcmp ( str , "" ) != 0 )
Insert ( str );
while ( scanf ( "%s" , str ) != EOF )
printf ( "%d \n " , Search ( str ));
Release ( root );
return 0 ;
}
This post is licensed under CC BY-NC-SA 4.0 . If it helped, or if you have anything to say, the comment box below is open. Page views
—
Unique visitors
—