#1400 : Composition
-
5 abcde 3 ac ab de
样例输出
-
2
描述
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'.
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include<climits>
#include<sstream>
#include<stack>
#include<unordered_map>
#include<list>
using namespace std;
bool mapp[27][27];
int dp[100001][27];
int solve_min(int a,int b) {
if(a==-1) return b;
return a<b?a:b;
}
int main() {
int n,m;
string input;
cin>>n;
cin>>input;
cin>>m;
memset(mapp,false,sizeof(mapp));
memset(dp,-1,sizeof(dp));
for(int i=0;i<m;i++) {
char s,e;
cin>>s>>e;
mapp[s-'a'][e-'a']=mapp[e-'a'][s-'a']=true;
}
dp[0][input[0]-'a']=0;
for(int i=1;i<n;i++) {
int index=input[i]-'a';
dp[i][index]=i;
for(int j=0;j<27;j++) {
if(dp[i-1][j]!=-1) {
dp[i][j]=solve_min(dp[i][j],dp[i-1][j]+1);
if(!mapp[index][j]) {
dp[i][index]=solve_min(dp[i][index],dp[i-1][j]);
}
}
}
}
int res=INT_MAX;
for(int i=0;i<27;i++) {
res=solve_min(dp[n-1][i],res);
}
cout<<res<<endl;
return 0;
}