Problem Address:http://cstfs.gdufs.edu.cn:8080/JudgeOnline/problem.jsp?id=1127
【前言】
学校OJ比赛的一道题。
貌似是USACO上面来的。
比赛时候想着字典树、AC自动机、再者加上DP什么的。
赛后看了几眼代码,老师说是DP,趁着解题报告还没出来把它A了。
【思路】
由于单词长度只有20,所以可以从这里下文章。
用20个字符串表示从当前位置开始可得到的最小字母序结果。
那么对于原字符串的每一个位置,枚举所有单词。
假设长度为len的单词可以匹配,则尝试更新当前位置加上len所对应的字符串。
尝试更新指的是如果比该字符串大则不可更新。
一个位置枚举完后,将所有字符串循环向1移动。即2移到1,3移到2……20移到19,而1则移到20。
之后进行下一个位置的判断。
如果当前位置为空串,则不可更新,但还是需要移动。
注意一:先枚举所有单词,把结果存到一个长度为20的数组里。然后再枚举这个数组来更新20个字符串,通过减少字符串的反复比较以降低复杂度。
注意二:20个字符串可以用指针来保存,那么移动的时候只需要移动指针即可。当然也可以用取模之类的来代替,看个人喜好。
【代码】
代码中附上一个case。
过了sample但还是WA,最后写了一个case。过了之后比较了才发现好像只是多了那么一行代码= =
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1030;
const int INF = 1000000;
const int kind = 20;
/*
20 5
a??ple??????????ple?
pleee
plef
abc
apl
e
abcpleeeabcabceaplee
*/
struct node
{
char w[kind+5];
int len;
}words[maxn+5];
bool cmp(const node &a, const node &b)
{
int t = strcmp(a.w, b.w);
if (t<0) return true;
else return false;
}
char org[maxn+5];
int tre[kind+5];
char *str[kind+5];
char strtemp[kind+5][maxn+5];
char *temp;
bool match(char *str, int s, int n, int len)
{
if (s+len>n) return false;
int i;
for (i=0; i<len; i++)
{
if (org[s+i]!='?' && org[s+i]!=str[i])
return false;
}
return true;
}
int main()
{
int i, j;
int n, m;
scanf("%d %d", &n, &m);
scanf("%s", org);
for (i=0; i<m; i++)
{
scanf("%s", words[i].w);
words[i].len = strlen(words[i].w);
}
sort(words, words+m, cmp);
memset(strtemp, 0, sizeof(strtemp));
for (i=1; i<=kind; i++) str[i] = strtemp[i];
str[1][0] = '\0';
for (i=0; i<n; i++)
{
if (i==0 || str[1][0]!='\0')
{
for (j=0; j<=kind; j++) tre[j] = INF;
for (j=0; j<m; j++)
{
if (j<tre[words[j].len] && match(words[j].w, i, n, words[j].len))
{
tre[words[j].len] = j;
}
}
temp = str[1];
for (j=1; j<kind; j++)
{
str[j] = str[j+1];
}
for (j=1; j<kind; j++)
{
if (tre[j]==INF)
{
continue;
}
strcat(temp, words[tre[j]].w);
if (tre[j]!=INF && (str[j][0]=='\0' || strcmp(temp, str[j])<0))
{
strcpy(str[j], temp);
}
temp[i] = '\0';
}
str[kind] = temp;
if (tre[kind]!=INF)
{
strcat(str[kind], words[tre[kind]].w);
}
else str[kind][0] = '\0';
}
else
{
temp = str[1];
for (j=1; j<kind; j++) str[j] = str[j+1];
str[kind] = temp;
}
}
printf("%s\n", str[1]);
return 0;
}