Equal Strings

2.5

17 votes
, Algorithms, Linear Search, Dynamic Programming
Problem

You are given two binary strings (where each character is either 0 or 1S and T, each of length N and an integer X. You can apply the following two types of operations to the string S:

  • Choose two distinct indices i,j and flip both Si,Sj. The cost of this operation is X.
  • Choose an index i(1i<N) and flip both Si,Si+1. The cost of this operation is 1.

You may perform this operation any number of times. Find the minimum cost to make the strings S and T equal or report that it is impossible.

 Input format

  • The first line of input contains an integer T denoting the number of test cases. The description of each test case is as follows:
  • The first line of each test case contains two integers N denoting the length of the string S and T and integer X.
  • The second line of each test case contains the string S.
  • The third line of each test case contains the string T.

Output format

For each test case, print 1 if it is impossible to equalize the strings. Otherwise print the minimum cost to make the strings S and T equal in a separate line.

Constraints

1T1001N,X2000S and T are binary strings.Sum of N over all test cases does not exceed 2000.

 

Sample Input
2
6 2
101011
010010
4 3
1010
0001
Sample Output
3
-1
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation
  • In the first test case, apply the first operation for i=3,j=6 with a cost of 2 making S=100010, then apply the second operation for i=1 making S=010010 which is equal to T. Hence the total cost is 2+1=3.
  • In the second test case, it is impossible to make S and T equal.
Editor Image

?