<pre name="code" class="cpp">#include<iostream>
#include <algorithm>
#include <queue>
#include <string>
#include <string.h>
using namespace std;
#define CHILD_NUM 2
#define MAXNODE 2000
#define MAXLINE 2000
int p = 0;
struct TrieNode
{
TrieNode *childs[CHILD_NUM];
int count;
};
TrieNode nodes[MAXNODE];
void insertNode(TrieNode *root, char *str)
{
TrieNode * pivot = root;
while (*str)
{
if (pivot->childs[*str - 'a'] == NULL)
{
pivot->childs[*str - 'a'] = &nodes[p++];
pivot->childs[*str - 'a']->count = 0;
}
pivot = pivot->childs[*str - 'a'];
pivot->count++;
str++;
}
}
//bool hasChild(TrieNode *r){
// bool hasChild = false;
// for (int i = 0; i < 26; i++)
// {
// if (r->childs[i] != nullptr)
// {
// hasChild = true;
// break;
// }
// }
// return hasChild;
//}
//void dfs(TrieNode *r,string s)
//{
// if (!hasChild(r))
// {
// cout << s << endl;
// return;
// }
// for (int i = 0; i < 26; i++)
// {
// if (r->childs[i] != nullptr)
// {
// s.push_back('a'+i);
// dfs(r->childs[i], s);
// s.pop_back();
// }
// }
//}
int ans = 0;
void dfs2(TrieNode *r, string s)
{
for (int i = 0; i < 26; i++)
{
TrieNode * child = r->childs[i];
if ( child != nullptr)
{
s.push_back('a' + i);
if (child->count <= 5)
{
//cout << s << endl;
ans++;
s.pop_back();
continue;
}
else
{
dfs2(r->childs[i], s);
s.pop_back();
}
}
}
}
int main(void)
{
char ar[10];
scanf_s("%s", ar);
int n = 0;
scanf_s("%d", &n);
char strs[100][1000] = {0};
for (int i = 0; i < n; ++i)
{
scanf_s("%s", &strs[i]);
fflush(stdin);
}
memset(nodes, 0, sizeof(nodes));
//char *strs[] = {"a","ab","abc","abcde","abcde","abcba","bcd","bcde","bcbbd","bcac","bee","bbb"};
TrieNode *r = new TrieNode();
for (int i = 0; i < n; i++)
{
insertNode(r, strs[i]);
}
//printTree(r);
dfs2(r, string(""));
cout << ans;
return 0;
}
//#include<iostream>
//using namespace std;
//const int Max = 1002;
//const int branchNum = 26;
//
//struct tree_node{
// int count; // 记录用到这个节点的单词数量,如果=1,则证明其为这个单词唯一的节点。
// tree_node *next[branchNum];
//}root, node[20 * Max];
//int p = 0;
//
//void insert(char *word){
// tree_node *location = &root;
// while (*word){
// if (location->next[*word - 'a'] == NULL){
// node[p].count = 0;
// location->next[*word - 'a'] = &node[p++];
// }
// location = location->next[*word - 'a'];
// location->count++;
// word++;
// }
//}
//
//void search(char *word){
// tree_node *location = &root;
// while (*word && location){
// if (location->count == 1) break;
// printf("%c", *word);
// location = location->next[*word - 'a'];
// word++;
// }
// printf("\n");
//}
//
//int main(){
// char word[Max][21];
// int i, k = 0;
// while (scanf_s("%s", word[k]) != EOF){
// insert(word[k]);
// k++;
// }
// for (i = 0; i < k; i++){
// printf("%s ", word[i]);
// search(word[i]);
// }
// return 0;
//}
微软笔试题-Shortest Proper Prefix
最新推荐文章于 2015-12-27 18:01:28 发布