An interesting question
Give you a string, and then give you a k pair of Characters
It is required to delete some characters so that there is no adjacent character in the string. This is a pair of K pairs.
First, if a character only appears in a pair of K pairs, You Can greedy
Because the following situations will not occur:
Aaaabbbcccc
2
AB
AC
That is, there will be no indentation after deletion, and there will be contradictions
But what if this happens?
DP comes in handy.
DP [I] [J] indicates the minimum characters to be deleted after the first I character is processed and the last character is (J + 'A ')
When it reaches an I position, it can be deleted no matter whether it is in conflict with the last character left behind.
If there is no conflict, we can also move the status to end with the current character
View code
# Include <cstdio> # Include <Cstring> # Include <Algorithm># Include < String > # Include <Iostream> # Include <Cmath> # Include <Cstdlib> # Include <Vector> # Include < Set > # Include <Map> # Include <Queue> # Include <Stack> Using Namespace STD; Const Int INF = ~ 0u > 2 ; Int Flag [ 27 ] [ 27 ]; Int DP [ 100010 ] [ 27 ]; Char S [ 100010 ]; Int Main (){ Int K; String OP; While (Scanf ( " % S " , S + 1 )! = EOF) {CIN > K; memset (flag, 0 , Sizeof (FLAG); fill (DP [ 0 ], DP [ 100001 ], INF ); While (K -- ) {CIN > OP; flag [op [ 0 ]- ' A ' ] [Op [ 1 ]-' A ' ] = 1 ; Flag [op [ 1 ]- ' A ' ] [Op [ 0 ]- ' A ' ] = 1 ;} DP [ 0 ] [26 ] = 0 ; Int Len = strlen (S + 1 ); For ( Int I = 1 ; I <= Len; I ++ ){ For ( Int J = 0 ; J <= 26 ; J ++)If (DP [I- 1 ] [J]! = INF ){ Int K = s [I]- ' A ' ; DP [I] [J] = Min (DP [I] [J], DP [I- 1 ] [J] + 1 ); // Delete the I character If (!Flag [J] [k]) {DP [I] [k] = Min (DP [I] [K], DP [I- 1 ] [J]); // No conflict. Do not delete it. }}} Int Ans = INF; For ( Int I = 0 ; I <= 26 ; I ++ ){ If (DP [Len] [I] < Ans) {ans = DP [Len] [I] ;}} printf ( " % D \ n " , ANS );} Return 0 ;}