0
点赞
收藏
分享

微信扫一扫

ZZULIOJ 1426: 字典树again【字典树+bfs】



1426: 字典树again


Time Limit: 1 Sec   Memory Limit: 128 MB

Submit: 247  

Solved: 48


​​Submit​​

​​Status​​

​​Web Board​​


Description


Gy最近学习了字典树结构,无聊的他又想到了一个新的问题,给定一个字符串集合S={str1, str2, …,strn}和一个字符串str,在str后接尽量少的字符,使其属于S。当然如果str本身属于S,str即为答案。


Input


第一行一个正整数T(T <= 10),表示有T组数据。

每组数据输入格式如下:

第一行为一个正整数N(0<N<20000),表示字符串集合内的字符串数。

接下来N行,每行一个字符串,表示集合中的串。

接下来一行是一个正整数Q(0<Q<200),表示有Q次询问。

接下来Q行,每行一个字符串str。

所有字符串均由小写英文字母组成,且1<=长度<=20。


Output


每组数据输出格式如下:

先输出“Case x:”,x表示是第几组数据,然后输出一个换行。

接下来输出Q行,对于每次询问,如果str能够添加字符使其属于字符串集合,则输出长度最小的(即str添加字符后构成的串),有多个满足条件的话输出字典序最小的。否则输出-1。


Sample Input


3



3



abc



abd



aba



3



ab



ad



abc



2



bcde



bcdef



1



bcd



3



abc



def



hig



1



kkkk


Sample Output


Case 1:



aba



-1



abc



Case 2:



bcde



Case 3:



-1


HINT



Source


​​郑轻第六届校赛​​

字典树的添加,删除-.-

查找字典树时用上bfs搜索-.-


代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,q;
char ji[22];
int bushu,bu;
char ch[22];
struct trie{
int shu;
struct trie *chilen[26];
char cchh[22];
};
trie boot;
void jia(char xx[])
{
struct trie *k=&boot;
int ll=strlen(xx);
for (int i=0;i<ll;i++)
{
if (!k->chilen[xx[i]-'a'])
{
k->chilen[xx[i]-'a']=new trie();
memset(k->chilen[xx[i]-'a'],0,sizeof(trie));
k->chilen[xx[i]-'a']->shu=0;
}
k=k->chilen[xx[i]-'a'];
}
k->shu=1;
strcpy(k->cchh,xx);
}
void bfs(struct trie *k)
{
if (k->shu==1)
{
if (bu<bushu)
{
strcpy(ji,k->cchh);
bushu=bu;
}
return;
}
for (int i=0;i<26;i++)
{
if (k->chilen[i])
{
bu++;
bfs(k->chilen[i]);
bu--;
}
}
}
void cha(char xx[])
{
struct trie *k=&boot;
int ll=strlen(xx);
for (int i=0;i<ll;i++)
{
if (!k->chilen[xx[i]-'a'])
{
printf("-1\n");
return;
}
k=k->chilen[xx[i]-'a'];
}
if (k->shu==1)
{
printf("%s\n",k->cchh);
return;
}
bushu=23;bu=0;
bfs(k);
printf("%s\n",ji);
}
void Fredom(struct trie *k)
{
for (int i=0;i<26;i++)
{
if (k->chilen[i])
Fredom(k->chilen[i]);
}
delete k;
}
int main()
{
int t;scanf("%d",&t);
for (int ca=1;ca<=t;ca++)
{
for (int i=0;i<26;i++)
boot.chilen[i]=0;
boot.shu=0;
scanf("%d",&n);
while (n--)
{
scanf("%s",ch);
jia(ch);
}
scanf("%d",&q);
printf("Case %d:\n",ca);
while (q--)
{
scanf("%s",ch);
cha(ch);
}
for (int i=0;i<26;i++)
if (boot.chilen[i])
Fredom(boot.chilen[i]);
}
return 0;
}



举报

相关推荐

0 条评论