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 靠近正能量的人 和什...
    持續收入倡導者閱讀 136評論 0 0
  • 《孕媽日記》目錄 歡迎戳進來 上一章 孕媽日記(九) 25 **孕28周+6天** **簡單的陪伴,簡單的祝福*...
    娜娜cai閱讀 245評論 0 1
  • 我追尋易安的足跡,追尋那個天真矜持的宦門少女的身影,追尋那個才情過人的、婉約清麗的閨閣少女的倩影,追尋那個終日凝眉...
    活出自己的調調閱讀 857評論 0 5
  • 回到學校后睡了一覺,醒來干凈床單和衣服袋子還在桌子上沒有整理,天卻已經黑了,我上一次低頭看到袋子們還是在下了公交之...
    亢龍有悔閱讀 206評論 0 2
  • 池邊柳樹碧玉妝, 半畝新荷水中央。 春風似解人心意, 吹過槐花一縷香。
    果殼大門不矮閱讀 127評論 1 4