题目链接:http://hihocoder.com/contest/mstest2016oct/problem/2
题意:给我们一些约束相邻的条件,让我们判断最少去掉多少个字符达到这个状态。
解题思路,因为都是小写字母,我们完全可以根据每个字母的约束条件,找到条件下的最长子串,答案就是长度减去这个最长子串的长度。
复杂度:26*n
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100000+10;
char str[maxn];
int G[30][30], dp[30];
int main()
{
int n, m;
while(scanf("%d", &n) !=EOF)
{
scanf("%s", str);
scanf("%d", &m);
memset(G,0,sizeof(G));
memset(dp,0,sizeof(dp));
for(int i=0; i<m; i++)
{
char a,b;
getchar();
scanf("%c%c", &a, &b);
G[a-'a'][b-'a'] = G[b-'a'][a-'a'] = 1;
}
for(int i=0; i<strlen(str); i++)
{
char a = str[i];
int tmp = 1;
for(int j=0; j<26; j++)
{
if(G[a-'a'][j]) continue;
tmp = max(tmp,dp[j]+1);
}
dp[a-'a'] = tmp;
}
sort(dp,dp+26);
printf("%d\n", n-dp[25]);
}
}