字典树模板题。
CODE:
字典树
#include <iostream>
using namespace std;
struct Trie
{
Trie *next[26];
int count, value;
Trie()
{
for(int i = 0; i < 26; i++)
next[i] = 0;
value = 0;
count = 1;
}
};
void insert(Trie *&root, char *s)
{
int i = 0, branch = 0;
Trie *p = root;
if(!p)
{
p = new Trie();
root = p;
}
while(s[i])
{
branch = s[i]-'a';
if(p->next[branch]) p->next[branch]->count++;
else p->next[branch] = new Trie();
p = p->next[branch];
i++;
}
p->value = 1;
}
int find(Trie *root, char *s)
{
int i = 0, branch = 0, ans;
Trie *p = root;
if(!p) return 0;
while(s[i])
{
branch = s[i]-'a';
if(!p->next[branch]) return 0;
p = p->next[branch];
ans = p->count;
i++;
}
return ans;
}
int main()
{
char save[11];
char ask[11];
Trie *root = NULL;
while(gets(save))
{
if(save[0] == '\0') break;
insert(root, save);
}
while(gets(ask))
{
printf("%d\n", find(root, ask));
}
return 0;
}
using namespace std;
struct Trie
{
Trie *next[26];
int count, value;
Trie()
{
for(int i = 0; i < 26; i++)
next[i] = 0;
value = 0;
count = 1;
}
};
void insert(Trie *&root, char *s)
{
int i = 0, branch = 0;
Trie *p = root;
if(!p)
{
p = new Trie();
root = p;
}
while(s[i])
{
branch = s[i]-'a';
if(p->next[branch]) p->next[branch]->count++;
else p->next[branch] = new Trie();
p = p->next[branch];
i++;
}
p->value = 1;
}
int find(Trie *root, char *s)
{
int i = 0, branch = 0, ans;
Trie *p = root;
if(!p) return 0;
while(s[i])
{
branch = s[i]-'a';
if(!p->next[branch]) return 0;
p = p->next[branch];
ans = p->count;
i++;
}
return ans;
}
int main()
{
char save[11];
char ask[11];
Trie *root = NULL;
while(gets(save))
{
if(save[0] == '\0') break;
insert(root, save);
}
while(gets(ask))
{
printf("%d\n", find(root, ask));
}
return 0;
}
CODE:
Map
#include <iostream>
#include <map>
#include <string.h>
using namespace std;
const int SIZE = 10;
map<string, int> Map;
char save[12];
char temp[12];
char ask[12];
char str[12];
void init()
{
int i, j;
Map.clear();
while(gets(temp))
{
if(temp[0] == '\n') break;
int len = strlen(temp);
if(len == 0) break;
for(i = 0; i < len; i++)
{
for(j = 0; j <= i; j++)
{
save[j] = temp[j];
}
save[j] = '\0';
strcpy(str, save);
Map[str]++;
}
}
return ;
}
int main()
{
init();
while(~scanf("%s", ask))
{
printf("%d\n", Map[ask]);
}
return 0;
}
#include <map>
#include <string.h>
using namespace std;
const int SIZE = 10;
map<string, int> Map;
char save[12];
char temp[12];
char ask[12];
char str[12];
void init()
{
int i, j;
Map.clear();
while(gets(temp))
{
if(temp[0] == '\n') break;
int len = strlen(temp);
if(len == 0) break;
for(i = 0; i < len; i++)
{
for(j = 0; j <= i; j++)
{
save[j] = temp[j];
}
save[j] = '\0';
strcpy(str, save);
Map[str]++;
}
}
return ;
}
int main()
{
init();
while(~scanf("%s", ask))
{
printf("%d\n", Map[ask]);
}
return 0;
}