握日啊,这题用G++提交就算释放了内存都MLE,害的我纠结了好几天。
模板题吧,感觉自己对结构体的用法还不是很灵活,加油吧。
#include <stdio.h>
#include <algorithm>
#include <map>
#include <stdlib.h>
#include <string.h>
using namespace std;
typedef long long LL;
const int N = 15;
const int INF = 1e8;
struct Trie
{
int sum;
Trie *next[26];
}*root;
void CreatTrie(char *str)
{
int len = strlen(str);
Trie *p = root, *q;
for(int i = 0; i < len; i ++)
{
int id = str[i] - 'a';
if(p -> next[id] == NULL)
{
q = new Trie;
q -> sum = 1;
for(int j = 0; j < 26; j ++)
{
q -> next[j] = NULL;
}
p -> next[id] = q;
p = p -> next[id];
}
else
{
p -> next[id] -> sum ++;
p = p -> next[id];
}
}
}
int FindTrie(char *str)
{
Trie *p;
int len = strlen(str);
p = root;
for(int i = 0; i < len; i ++)
{
int id = str[i] - 'a';
p = p -> next[id];
if(p == NULL) return 0;
}
return p -> sum;
}
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;
}
int main()
{
// freopen("in.txt", "r", stdin);
int t, num;
char s[N], str[N];
root = new Trie;
root -> sum = 0;
for(int i = 0; i < 26; i ++)
{
root -> next[i] = NULL;
}
while(gets(s) && s[0] != '\0')
{
CreatTrie(s);
}
while(~scanf("%s", str))
{
int ans = FindTrie(str);
printf("%d\n", ans);
}
Release(root);
return 0;
}
后来想了想还是这个模板更加简洁。
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 15;
const int INF = 1e8;
struct Trie
{
int sum;
bool exist;
Trie *next[26];
Trie()
{
exist = 0;
sum = 0;
for(int i = 0; i < 26; i ++)
next[i] = 0;
}
}root;
void inserttrie(char *str)
{
int k = 0;
Trie *p = &root;
while(str[k] != '\0')
{
int id = str[k] - 'a';
if(p -> next[id] == 0) p -> next[id] = new Trie;
p = p -> next[id];
p -> sum ++;
k ++;
}
p -> exist = 1;
}
int findtrie(char *str)
{
int k = 0;
Trie *p = &root;
while(str[k] != '\0' && p -> next[str[k] - 'a']) p = p -> next[str[k ++] - 'a'];
return str[k] == '\0' ? p -> sum : 0;
}
int main()
{
// freopen("in.txt", "r", stdin);
char s[N];
while(gets(s) && s[0] != '\0') inserttrie(s);
while(~scanf("%s", s)) printf("%d\n", findtrie(s));
return 0;
}