词典 字符串+DP

【问题描述】
或许你还没发现,山山有一本古老的词典。
而且他说的每一个单词必然存在于这本字典中。可是由于听力问题,你听到的单词会夹杂着
一些不该有的发音。
例如听到的:
somutchmoreaweare
可能是:
so much more aware
山山的词典里有 n 个单词,你听到一句长度为 m 的话
请你判断这句话最少有几个杂音
【输入文件】
输入文件 dictionary.in 的第 1 行包含 2 个正整数 n,m
第 2 行包含一个长度为 m 的小写字符串 s
接下来 n 行,每行是一个小写单词 ti
【输出文件】
输出文件 dictionary.out 仅包含一个正整数数,最少的杂音数
【样例输入】
5 17
somutchmoreaweare
so
much
more
aware
numb
【样例输出】
2
【数据规模】
对于前 20%的数据 n≤20,m≤20,|ti|≤20
对于前 40%的数据 n≤100,m≤100,|ti|≤100
对于 100%的数据 n≤600,m≤300,|ti|≤300


 

因为没做过这种题目,我开始根本是懵逼的,最后看了题解才会做。

dp[i]表示匹配到 i 最少含几个杂音
dp[i]可以更新后面的 dp[j],倒着更新效果更好。
dp[i] = min(dp[i] , dp[i + len[j] + t] + t) 表示 i 后面的字符串匹配第 j 个单词有 t 个杂音,t 可
以用一个字符串匹配函数求得。

其他的就是注意dp初始值了。。。

代码:

 

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>

#define ll long long
#define il inline
#define db double

using namespace std;

int n,m;

char chuan[1045];

char hzr[645][345];

int len[645];

int f[1045];

il int check(int x,int y)
{
	int now=0,p=x;
	bool flag=0;
	while(now!=len[y])
		{
			if(x>=m)
				break;
			if(chuan[x]==hzr[y][now])
				now++;
			if(now==len[y])
				flag=1;
			x++;
		}
	if(flag==1)
		return x-p-len[y];
	else
		return -1;
}

int main()
{
	freopen("dictionary.in","r",stdin);
	freopen("dictionary.out","w",stdout);

	memset(f,127/3,sizeof(f));

	cin>>n>>m;

	scanf("%s",chuan);

	for(int i=1;i<=n;i++)
		{
			scanf("%s",hzr[i]);
			len[i]=strlen(hzr[i]);
		}
	
	f[m]=0;
	for(int i=m-1;i>=0;i--)
		{
			f[i]=f[i+1]+1;
			for(int j=1;j<=n;j++)
				{
					int t=check(i,j);
					if(t==-1)
						continue;
					f[i]=min(f[i],f[i+len[j]+t]+t);
				}
		}

	printf("%d\n",f[0]);

	return 0;
}

 

posted @ 2017-10-18 16:02  GSHDYJZ  阅读(219)  评论(0编辑  收藏  举报