2017微软秋季校园招聘在线编程笔试(二)

题目2 : Composition

  • 时间限制:10000ms
  • 单点时限:1000ms
  • 内存限制:256MB

描述
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
参考答案1:

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef pair<int, int> pii;
#define fst first
#define snd second

const int MAXN = 100010;
bool can[30][30];
int dp[100010][30];

int main(void) {

    int n;
    cin >> n;
    string s;
    cin >> s;

    for (int i = 0; i < 26; ++ i) for (int j = 0; j < 26; ++ j) can[i][j] = true;
    int m;
    cin >> m;
    for (int i = 0; i < m; ++ i) {
        string t;
        cin >> t;
        can[t[0]-'a'][t[1]-'a'] = false;
        can[t[1]-'a'][t[0]-'a'] = false;
    }

    memset(dp, 0x3f, sizeof(dp));
    vector<int> lst(26, 0);
    lst[s[0] - 'a'] = 1;
    dp[1][s[0] - 'a'] = 0;
    for (int i = 2; i <= n; ++ i) {
        for (int j = 0; j < 26; ++ j) {
            dp[i][j] = dp[i - 1][j] + 1;
        }

        int ch = s[i - 1] - 'a';
        for (int j = 0; j < 26; ++ j) if (can[ch][j] && lst[j]) {
            dp[i][ch] = min(dp[i][ch], dp[lst[j]][j] + i - lst[j] - 1);
        }
        dp[i][ch] = min(dp[i][ch], i - 1);

        lst[ch] = i;
    }

    int ans = n;
    for (int i = 0; i < 26; ++ i) ans = min(ans, dp[n][i]);
    cout << ans << endl;

    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 去靠近一个给你正能量的人 2017-05-17 靠近正能量的人 和什...
    持续收入倡导者阅读 135评论 0 0
  • 《孕妈日记》目录 欢迎戳进来 上一章 孕妈日记(九) 25 **孕28周+6天** **简单的陪伴,简单的祝福*...
    娜娜cai阅读 245评论 0 1
  • 我追寻易安的足迹,追寻那个天真矜持的宦门少女的身影,追寻那个才情过人的、婉约清丽的闺阁少女的倩影,追寻那个终日凝眉...
    活出自己的调调阅读 853评论 0 5
  • 回到学校后睡了一觉,醒来干净床单和衣服袋子还在桌子上没有整理,天却已经黑了,我上一次低头看到袋子们还是在下了公交之...
    亢龙有悔阅读 205评论 0 2
  • 池边柳树碧玉妆, 半亩新荷水中央。 春风似解人心意, 吹过槐花一缕香。
    果壳大门不矮阅读 127评论 1 4