POJ 3267 The Cow Lexicon dp

本文介绍了一个使用动态规划解决字符串匹配问题的算法实现。通过输入目标字符串和多个模式串,算法能够找出最小代价的匹配方案。代码中运用了C++语言,并详细展示了如何逐字符比较并更新状态转移矩阵。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

算法想不出来。。看得杨的blog杨大神

代码如下

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#define inf 0x3f3f3f3f

using namespace std;

char s[800];
char str[800][800];
int dp[800];
int len[800];

int main()
{
    int n, l;
    int i, j;
    while(cin >> n >> l){
        memset(dp,0,sizeof(dp));
        scanf("%s", s);
        for(i = 0;i < n;i++){
            scanf("%s", str[i]);
            len[i] = strlen(str[i]);
        }
        for(i = l-1;i >= 0;i--){
            dp[i] = dp[i+1]+1;
            for(j = 0;j < n;j++){
                if(str[j][0]==s[i]&&l-i>=len[j]){
                    int ss = i;
                    int t = 0;
                    while(ss < l){
                        if(str[j][t]==s[ss]){
                            t++;
                        }
                        ss++;
                        if(t==len[j]){
                            dp[i] = min(dp[i],dp[ss]+ss-i-len[j]);
                            break;
                        }
                    }
                }
            }
        }
        printf("%d\n", dp[0]);
    }

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值