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: Accepted)

#include<bits/stdc++.h>
using namespace std;

char s[2020],t[2020];
int n,pre[2020],nex[2020],pd[2020],nd[2020],p,ans,x[2020],y[2020];
vector<int>v[2020];

void f__k(){
	int fl=0; for (int i=0;i<n;i++) fl|=s[i]-'0';
	exit(0*puts(fl?"-1":"0")); 
}
int fix(int x) { return (x%n+n)%n; }

int cal(){
	for (int i=0;i<n;i++) v[i].clear();
	for (int i=0;i<n;i++) v[x[i]].push_back(i);
	int mx=0,res=1e6;
	for (int i=n-1;i>=0;i--){
		res=min(res,i+mx);
		for (int j:v[i]) mx=max(mx,y[j]);
	}
	return res;
}

int doit(int c){
	int res=abs(c); for (int i=0;i<n;i++) res+= s[i]!=t[fix(i+c)];
	memcpy(x,pd,sizeof x); memcpy(y,nd,sizeof y);
	for (int i=0;i<n;i++) c<0? x[i]=max(x[i]+c,0): y[i]=max(y[i]-c,0);
	return res+2*cal();
}

int main(){
	scanf("%s%s",s,t); n=strlen(s);
	for (p=0;t[p]=='0';p++);
	if (p==n) f__k();
	nex[n-1]= t[n-1]=='1'? n-1: p;
	for (int i=n-2;i>=0;i--) nex[i]= t[i]=='1'? i: nex[i+1];
	for (p=n-1;t[p]=='0';p--);
	pre[0]= t[0]=='1'? 0: p;
	for (int i=1;i<n;i++) pre[i]= t[i]=='1'? i: pre[i-1];
	for (int i=0;i<n;i++) pd[i]=s[i]=='1'? fix(i-pre[i]): 0, nd[i]=s[i]=='1'? fix(nex[i]-i): 0;
	ans=1e6; for (int i=1-n;i<=n-1;i++) ans=min(ans,doit(i));
	cout<<ans;
}