菜鸟要从水做起
Let the Balloon Rise 我用的静态字典树(动态的没看懂),题意是找出气球颜色多的输出,所以只需要字典树的一步“插入单词”函数就可完成。
字典树的意思就是先给一个根节点,然后顺着这条根节点往下连接儿子节点的那条边作为单词的一个字母,如果存在这个字母就下去找那个儿子节点,然后同理找下一个字母。不存在这个字母的话,根节点就再生一个儿子,然后继续不断地生..查找同理,字母不存在就说明没这个单词
本题的水代码
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <math.h>
#include <map>
#include <algorithm>
using namespace std;
char s[20], ans[20];
int ch[1500][26];
int val[1500];
int tot, maxx;
void insert(char *a, int rt)
{
for (int i = 0; a[i]; i++)
{
int x = a[i] - 'a';
if (ch[rt][x] == 0)
{
ch[rt][x] = tot++;
}
rt = ch[rt][x];
}
val[rt]++;
if (maxx < val[rt])
{
maxx = val[rt];
strcpy(ans, a);
}
}
int main()
{
int n;
while (scanf("%d", &n) == 1 && n)
{
int i;
tot = 0, maxx = 0;
memset(val, 0, sizeof val);
memset(ch[1], 0, sizeof(ch[1]));
for (i = 0; i < n; i++)
{
scanf("%s", s);
insert(s, 1);
}
printf("%s\n", ans);
}
return 0;
}
附一个学长给的静态字典树模板
#include <stdio.h>
#include <string.h>
const int maxn=10000;//提前估计好可能会开的节点的个数
int tot; //节点编号,模拟申请新节点,静态申请
int trie[maxn][26]; //假设每个节点的分支有26个
bool isw[maxn]; //判断该节点是不是单词结尾
void insert(char *s,int rt){
for(int i=0;s[i];i++){
int x=s[i]-'a';//假设单词都是小写字母组成
if(trie[rt][x]==0){//没有,申请新节点
trie[rt][x]=++tot;
}
rt=trie[rt][x];
}
isw[rt]=true;
}
bool find(char *s,int rt){
for(int i=0;s[i];i++){
int x=s[i]-'a';//假设单词都是小写字母组成
if(trie[rt][x]==0){
return false;
}
rt=trie[rt][x];
}
return isw[rt];
}
char s[22];//单词读入
int main(){
tot=0;//一开始没有节点
int rt=++tot;//申请一个根节点
memset(trie[rt],0,sizeof(trie[rt]));//初始化根节点
memset(isw,false,sizeof(isw));
while(scanf("%s",s),s[0]!='#'){//新建字典,以一个'#'结束
insert(s,rt);
}
while(scanf("%s",s),s[0]!='#'){//查单词,以一个'#'结束
if(find(s,rt))
printf("%s 在字典中\n",s);
else
printf("%s 不在字典中\n",s);
}
return 0;
}