topic link
analyze
It should not be difficult to think of DP
in characters The maximum length that can be saved at the end must be the optimal solution that can be saved at the end of the previous character
Assume
: in characters The maximum string length that can be stored at the end.
then iterate over the entire string, for each character in it
java code
import java.io.BufferedInputStream;
import java.nio.MappedByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static final int INF = 0x3f3f3f3f;
public static Scanner in = new Scanner(new BufferedInputStream(System.in));
public static void main(String[] args) {
String string;
boolean[][] map = new boolean[27][27];
for(int i='a' ; i<='z' ; ++i)
for(int j='a' ; j<='z' ; ++j)map[i-'a'][j-'a'] = true;
in.nextLine();
string = in.nextLine();
while (string=="")string = in.nextLine();
int k = in.nextInt();
while (k-->0) {
String string2 = in.nextLine();
while (string2.equals(""))string2 = in.nextLine();
int u = string2.charAt(0)-'a';
int v = string2.charAt(1) - 'a';
map[u][v] = map[v][u] = false;
}
System.out.println(new Solution(string, map).solve());
}
}
class Solution {
String string;
boolean[][] map;
int[] cnt;
public Solution(String string, boolean[][] map) {
super();
this.string = string;
this.map = map;
cnt = new int['z'+10];
for(int i='a' ; i<='z' ; ++i)cnt[i] =0;
}
public int solve() {
for(int i=0 ; i<string.length() ; ++i){
char now = string.charAt(i);
int tmp =0;
for(int j='a' ; j<='z' ; ++j){
if(map[now-'a'][j-'a'])tmp = Math.max(tmp, cnt[j]+1);
}
cnt[now] = Math.max(tmp, cnt[now]);
}
int ret =0;
for(int i='a' ; i<'z' ; ++i)ret = Math.max(ret, cnt[i]);
return string.length()-ret;
}
}