Problem:
Score : 1000 points

Problem Statement

You have two strings A = A_1 A_2 ... A_n and B = B_1 B_2 ... B_n of the same length consisting of 0 and 1.

You can transform A using the following operations in any order and as many times as you want:

Shift A by one character to the left (i.e., if A = A_1 A_2 ... A_n, replace A with A_2 A_3 ... A_n A_1).

Shift A by one character to the right (i.e., if A = A_1 A_2 ... A_n, replace A with A_n A_1 A_2 ... A_{n-1}).

Choose any i such that B_i = 1. Flip A_i (i.e., set A_i = 1 - A_i).

You goal is to make strings A and B equal.

Print the smallest number of operations required to achieve this, or -1 if the goal is unreachable.

Constraints

1 \leq |A| = |B| \leq 2,000

A and B consist of 0 and 1.

Input

Input is given from Standard Input in the following format:

A
B

Output

Print the smallest number of operations required to make strings A and B equal, or -1 if the goal is unreachable.

Sample Input 1

1010
1100

Sample Output 1

3

Here is one fastest way to achieve the goal:

Flip A_1: A = 0010

Shift A to the left: A = 0100

Flip A_1 again: A = 1100

Sample Input 2

1
0

Sample Output 2

-1

There is no way to flip the only bit in A.

Sample Input 3

11010
10001

Sample Output 3

4

Here is one fastest way to achieve the goal:

Shift A to the right: A = 01101

Flip A_5: A = 01100

Shift A to the left: A = 11000

Shift A to the left again: A = 10001

Sample Input 4

0100100
1111111

Sample Output 4

5

Flip A_1, A_3, A_4, A_6 and A_7 in any order.

Solution in C++14 (GCC 5.4.1) (judge verdict: Wrong Answer)

#include<bits/stdc++.h>
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define N 5005
#define lowbit(o) o&(-o)
using namespace std;
int i,j,k,l,s,n,m,R[N],L[N],q[N],ans,G[N],r;
int a[N],b[N],test,qq[N],f[N];
char c[N];
inline bool cmp(int x,int y) {
	return R[x]<R[y];
}
inline void Sort() {
	for (int i=0;i<=n+1;i++) f[i]=0;
	for (int i=1;i<=r;i++) f[R[q[i]]+1]++;
	for (int i=1;i<=n+1;i++) f[i]+=f[i-1];
	for (int i=1;i<=r;i++) qq[++f[R[q[i]]]]=q[i];
	for (int i=1;i<=r;i++) q[i]=qq[i];
}
int main() {
//	scanf("%d",&test);
test=1;
	while (test--) {
		scanf("%s",c+1);
		n=strlen(c+1);
		for (i=1;i<=n;i++) a[i]=c[i]-48,L[i]=R[i]=100000000;
		scanf("%s",c+1);
		for (i=1;i<=n;i++) b[i]=c[i]-48;
		for (i=1;i<=n;i++) for (j=1;j<=n;j++) if (b[j]) L[i]=min(L[i],(i-j+n)%n),R[i]=min(R[i],(j-i+n)%n);
		if (L[n]==100000000) {
			puts("-1"); continue;
		}
		ans=100000000;
		for (i=1;i<=n;i++) {
			r=0; k=i;
			for (j=1;j<=n;j++) {
				if (a[k]!=b[j]) q[++r]=k;
				k%=n; k++;
			}
			//sort(q+1,q+1+r,cmp);
			Sort();
			G[r+1]=0;
			for (k=r;k;k--) G[k]=max(G[k+1],L[q[k]]);
			for (k=0;k<=r;k++) {
				//workL:
				ans=min(ans,(R[q[k]]+max((i-j+n)%n,G[k+1]))*2-(i-j+n)%n+r);
				//workR:
				ans=min(ans,(G[k+1]+max((j-i+n)%n,R[q[k]]))*2-(j-i+n)%n+r);
			}
		}
		printf("%d\n",ans);
	}
}