poj 3267 动态规划
来源:互联网 发布:邮储银行网络 编辑:程序博客网 时间:2024/06/03 13:51
Description
Few know that the cows have their own dictionary with W (1 ≤ W ≤ 600) words, each containing no more 25 of the characters 'a'..'z'. Their cowmunication system, based on mooing, is not very accurate; sometimes they hear words that do not make any sense. For instance, Bessie once received a message that said "browndcodw". As it turns out, the intended message was "browncow" and the two letter "d"s were noise from other parts of the barnyard.
The cows want you to help them decipher a received message (also containing only characters in the range 'a'..'z') of length L (2 ≤ L ≤ 300) characters that is a bit garbled. In particular, they know that the message has some extra letters, and they want you to determine the smallest number of letters that must be removed to make the message a sequence of words from the dictionary.
Input
Line 2: L characters (followed by a newline, of course): the received message
Lines 3..W+2: The cows' dictionary, one word per line
Output
Sample Input
6 10browndcodwcowmilkwhiteblackbrownfarmer
Sample Output
2
Source
题意就是给出一个主串,和一本字典,问最少在主串删除多少字母,可以使其匹配到字典的单词序列。
主要是知道状态方程的含义
dp[i]表示从p中第i个字符开始,到第L个字符(结尾处)这段区间所删除的字符数,初始化为dp[L]=0
从程序可以看出,第i个位置到L所删除的字符数,总是先取最坏情况,只有可以匹配单词时才进入第二条方程进行状态优化更新。
第一条方程不难理解,只要弄懂dp[i]的意义就能简单推导
第二条方程难点在dp[pm]+(pm-i)-len
从程序知道,pm是message的指针(其中i表示当前所匹配的单词在message中的起始位置),pd是字典的指针
匹配的过程是:
当确认message第i位和某单词的首位吻合时,就开始逐字匹配,字符相同则两个指针同时向后移动一次,否则pd固定,pm移动。当因为pm>L跳出匹配时,说明匹配失败,dp[i]状态不变;当pd==单词长度时,单词匹配成功,进行dp[i]的状态优化
显然,匹配成功时,pm-i代表匹配过程中,从位置i到pm的区间长度,再减去单词长度len,则得到从i到pm所删除的字符数(pm-i)-len。又dp[pm]表示从pm到L所删除的字符数(根据检索方向,dp[pm]的值在此前已经被作为最坏打算处理,因此并不是空值)
从而dp[pm]+(pm-i)-len表示i到L删除的字符数,不难证明这个值一定比dp[i]相等或更优,因此取min赋值给dp[i]
最后输出dp[0]就可以了。
#include<iostream>#include<stdio.h>#include<iomanip>#include<string>using namespace std;int W,L;string dic[3010];char word[7000];int dp[7000];void init(){cin>>W>>L;for (int i = 0; i < L; i++){char temp;cin>>temp;word[i]=temp;}for(int i=0;i<W;i++){char buf[700]; scanf("%s", &buf); dic[i]=buf;}}int main(){init();int i,j,k;dp[L]=0;for( i=L-1;i>=0;i--){dp[i]=dp[i+1]+1;for(j=0;j<W;j++){int len=dic[j].length();if (len<=L-i&&dic[j][0]==word[i]){int p=i+1,q=1;while(true){if (q==len){dp[i]=min(dp[i],dp[p]+p-i-len);break;}if (p>=L){break;}if (dic[j][q]!=word[p]){p++;}else p++,q++;}}}}cout<<dp[0]<<endl;}
- POJ 3267 动态规划
- poj 3267 动态规划
- poj 3267 动态规划
- poj 3267(动态规划)
- POJ 3267-The Cow Lexicon 动态规划
- POJ 3267 The Cow Lexicon 动态规划
- poj 3267 The Cow Lexicon动态规划
- poj 3267 The Cow Lexicon (动态规划)
- poj 2411 动态规划
- Poj 1157(动态规划)
- POJ 1651动态规划
- Poj 1221 动态规划
- POJ 3186 动态规划
- [poj]动态规划2479
- [poj]动态规划1015
- [poj] 动态规划 1141
- POJ 1088 动态规划
- poj 1636 动态规划
- Linux上的Shell之FAQ
- rpm安装文件制作和使用
- 免费好用的Diff和Merge工具大总结
- Apache与Tomcat整合
- web服务器和应用服务器概念比较
- poj 3267 动态规划
- KDE/QT与GNOME/GTK比较
- Linux下patch的制作和应用
- net use 使用
- robocopy帮助
- linux configure使用方法
- [在windows上使用Unix工具]cygwin
- 批处理Dos命令
- Linux系统信息查看