2017微軟秋季校園招聘在線編程筆試(第二題)

時間限制: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

解題思路:

        一個動態規劃的題目,f[i]代表以第i個字母(0-25)結尾的最長的子串,對於字符串上每一個字符k都有刪和不刪兩種選擇,如果刪除,則f[i]不變,如果不刪除,則f[k]爲滿足不相鄰的條件的最長的f[i]+1。

代碼:

#include <cstdio>
#include <cstring>

using namespace std;

int n,m;
char s[100005];
bool a[30][30];
int f[30];

int main()
{
    scanf("%d",&n);
    scanf("%s",s);
    scanf("%d",&m);
    memset(a,true,sizeof(a));
    for(int i = 0; i < m; i ++){
        char temp[10];
        scanf("%s",temp);
        a[temp[0]-'a'][temp[1]-'a'] = false;
        a[temp[1]-'a'][temp[0]-'a'] = false;
    }
    memset(f,0,sizeof(f));
    int length = strlen(s);
    for(int i = 0; i < length ; i ++){
        int maxN = 0;
        for(int j = 0; j < 26; j ++){
            if(f[j] > maxN && a[j][s[i] - 'a']) maxN = f[j];
        }
        f[s[i] - 'a'] = maxN + 1;
    }
    int ans = 0;
    for(int i = 0; i < 26; i ++){
        if(f[i] > ans) ans = f[i];
    }
    printf("%d\n",length - ans);
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章