每日一题之 hiho201 Composition

该文章探讨了一道编程题目,要求在给定的英文作文中删除最少数量的字符,以确保没有教师定义的非法字符对相邻。通过分析样例和提供O(26N)复杂度的解决方案,文章揭示了如何使用动态规划优化算法来解决这个问题。

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

描述
Alice writes an English composition with a length of N characters. However, her teacher requires that M illegal pairs of characters cannot be adjacent, and if ‘ab’ cannot be adjacent, ‘ba’ cannot be adjacent either.

In order to meet the requirements, Alice needs to delete some characters.

Please work out the minimum number of characters that need to be deleted.

输入
The first line contains the length of the composition N.

The second line contains N characters, which make up the composition. Each character belongs to ‘a’..’z’.

The third line contains the number of illegal pairs M.

Each of the next M lines contains two characters ch1 and ch2,which cannot be adjacent.

For 20% of the data: 1 ≤ N ≤ 10

For 50% of the data: 1 ≤ N ≤ 1000

For 100% of the data: 1 ≤ N ≤ 100000, M ≤ 200.

输出
One line with an integer indicating the minimum number of characters that need to be deleted.

样例提示
Delete ‘a’ and ‘d’.

样例输入
5
abcde
3
ac
ab
de
样例输出
2

题意:

给出一个长度为n的字符串序列,并且给定m个非法的字符对,假如‘ab’非法,那么‘ba’也是非法的,求最少删除几个字符使得序列合法。

思路:

本题最暴力的解法就是枚举哪些字符被删掉。枚举的复杂度是O(2^N),再加上O(N)的判断,总复杂度是 O(N2N) O ( N 2 N )

比较容易想到的是 O(N2) O ( N 2 ) 的DP。(表示知道应该是DP做但是思维还是没锻炼出来,不知道怎么D)

由于删掉最少等价于留下最多,所以我们可以用f[i]表示最后留下一个字符是S[i]时,最多留下多少个字符。

要求f[i],我们只需要枚举S[i]之前的一个字符是哪个,并且从中选择合法并且最优的解:

f[i] = max{f[j]} + 1, for j = 1 .. i-1且S[j]S[i]不是”illegal pair”。
就算是 N2 N 2 的复杂度 N 最大到 10000也过不了,只能继续优化。

求f[i]时,需要枚举之前所有的位置j,但实际上之前的字符只有’a’~’z’26种可能。对于相同的字符,我们只用考虑最后一次它出现的位置,之前的位置一定不是最优。

例如,假设s[2] = s[5] = s[8] = ‘h’,那么当i>8时,我们求f[i]根本不用考虑j=2和j=5的情况,这两种情况即便合法也不会比j=8更优。

于是我们每次求f[i]只需要考虑’a’~’z’最后一次出现的位置。复杂度可以优化到O(26N)。

#include <cstdio>
#include <iostream>
#include <vector>
#include <map>
#include <cstring>
#include <algorithm>

using namespace std;

const int maxn = 1e6+5;



int dp[maxn];

int main()
{
    int n,m;
    string str;
    map<string,int>S;
    cin >> n;
    cin >> str;
    cin >> m;

    int pos[30];
    bool illegal[30][30];

    memset(pos,-1,sizeof(pos));
    memset(illegal,0,sizeof(illegal));


    for (int i = 0; i < m; ++i) {
        string s;
        cin >> s;
        illegal[s[0]-'a'][s[1]-'a'] = 1;
        illegal[s[1]-'a'][s[0]-'a'] = 1;

    }


    int res = 0;
    for (int i = 0; i < n; ++i) {
        dp[i] = 1;
        for (int j = 0; j < 26; ++j) {

            if (pos[j]!= -1 && (!illegal[j][str[i]-'a'] || !illegal[str[i]-'a'][j])) {

                dp[i] = max(dp[pos[j]]+1,dp[i]);

            }

        }
        pos[str[i]-'a'] = i;

    }

    for (int i = 0; i < n; ++i)
        res = max(res,dp[i]);
    cout << n - res << endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值