import static java.
lang .
Math .
min ;
public class ManageSubsequences {
final int INF = 1000 * 1000 * 1000 + 5 ;
int [ ] [ ] dp = new int [ A.length ( ) + 1 ] [ B.length ( ) + 1 ] ;
for ( int i = 0 ; i <= A.length ( ) ; ++ i)
for ( int j = 0 ; j <= B.length ( ) ; ++ j)
dp[ i] [ j] = INF;
dp[ 0 ] [ 0 ] = 0 ;
for ( int ii = 0 ; ii <= S.length ( ) ; ++ ii) {
for ( int i = 0 ; i < A.length ( ) ; ++ i)
for ( int j = 0 ; j < B.length ( ) ; ++ j) {
int i2 = i + 1 ;
int j2 = j + ( A.charAt ( i) == B.charAt ( j) ? 1 : 0 ) ;
dp[ i2] [ j2] = min( dp[ i2] [ j2] , dp[ i] [ j] + 1 ) ;
}
if ( ii == S.length ( ) )
break ;
char must = S.charAt ( ii) ;
for ( int i = A.length ( ) ; i >= 0 ; -- i)
for ( int j = B.length ( ) - 1 ; j >= 0 ; -- j) {
int x = dp[ i] [ j] ;
dp[ i] [ j] = INF;
int i2 = i + ( i < A.length ( ) && must == A.charAt ( i) ? 1 : 0 ) ;
int j2 = j + ( must == B.charAt ( j) ? 1 : 0 ) ;
dp[ i2] [ j2] = min( dp[ i2] [ j2] , x) ;
}
}
int best = INF;
for ( int i = 0 ; i < B.length ( ) ; ++ i)
best = min( best, dp[ A.length ( ) ] [ i] ) ;
if ( best == INF) best = - 1 ;
return best;
}
}
aW1wb3J0IHN0YXRpYyBqYXZhLmxhbmcuTWF0aC5taW47CgpwdWJsaWMgY2xhc3MgTWFuYWdlU3Vic2VxdWVuY2VzIHsKCWZpbmFsIGludCBJTkYgPSAxMDAwICogMTAwMCAqIDEwMDAgKyA1OwoJcHVibGljIGludCBtaW5BZGRlZChTdHJpbmcgUywgU3RyaW5nIEEsIFN0cmluZyBCKSB7CgkJaW50W11bXSBkcCA9IG5ldyBpbnRbQS5sZW5ndGgoKSsxXVtCLmxlbmd0aCgpKzFdOwoJCWZvcihpbnQgaSA9IDA7IGkgPD0gQS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