题目
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.
给定一个由小写字母组成的字符串,规定某些字符不能相邻。求最少需要删除多少个字符使得剩下的字符串中不存在那些规定不能相邻的字符相邻。
解法
dp[ch] = max(dp[ch], dp[t] + 1) t为a-z,且t和ch可以相邻。这样,在从头到尾扫描完一遍字符串,得到dp数组之后,最少需要删除的字符的个数就等于 n(原来字符串长度) - max(dp[c]).
#include<stdio.h>
#include<string>
#include<iostream>
#include<algorithm>
#include<functional>
#include<queue>
#include<vector>
#include<set>
#include<list>
#include<unordered_map>
#include<unordered_set>
#include<stack>
#include<map>
#include<algorithm>
#include<string.h>
using namespace std;
char str[1000005];
int dp[26];
int n;
bool table[26][26];
int main(){
scanf("%d", &n);
scanf("%s", str);
memset(dp, -1, sizeof(dp));
int k;
scanf("%d", &k);
char word[4];
for (int i = 0; i < k; i++){
scanf("%s", word);
table[word[0] - 'a'][word[1] - 'a'] = true;
table[word[1] - 'a'][word[0] - 'a'] = true;
}
for (int i = 0; i < n; i++){
int cur = str[i] - 'a';
int tmp = 1;
for (int j = 0; j < 26; j++){
if (table[cur][j])
continue;
tmp = max(tmp, dp[j] + 1);
}
dp[cur] = tmp;
}
int tmp = 0;
for (int i = 0; i < 26; i++)
tmp = max(tmp, dp[i]);
printf("%d\n", n - tmp);
return 0;
}