Problem:
Score : 1500 points

Problem Statement

#nck {
width: 30px;
height: auto;
}

Shik's job is very boring. At day 0, his boss gives him a string S_0 of length N which consists of only lowercase English letters. In the i-th day after day 0, Shik's job is to copy the string S_{i-1} to a string S_i. We denote the j-th letter of S_i as S_i[j].

Shik is inexperienced in this job. In each day, when he is copying letters one by one from the first letter to the last letter, he would make mistakes. That is, he sometimes accidentally writes down the same letter that he wrote previously instead of the correct one. More specifically, S_i[j] is equal to either S_{i-1}[j] or S_{i}[j-1]. (Note that S_i[1] always equals to S_{i-1}[1].)

You are given the string S_0 and another string T.
Please determine the smallest integer i such that S_i could be equal to T. If no such i exists, please print -1.

Constraints

1 \leq N \leq 1,000,000

The lengths of S_0 and T are both N.

Both S_0 and T consist of lowercase English letters.

Input

The input is given from Standard Input in the following format:

N
S_0
T

Output

Print the smallest integer i such that S_i could be equal to T. If no such i exists, print -1 instead.

Sample Input 1

5
abcde
aaacc

Sample Output 1

2

S_0 = abcde, S_1 = aaccc and S_2 = aaacc is a possible sequence such that S_2 = T.

Sample Input 2

5
abcde
abcde

Sample Output 2

0

Sample Input 3

4
acaa
aaca

Sample Output 3

2

Sample Input 4

5
abcde
bbbbb

Sample Output 4

-1

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

//by xiqiao
#include<bits/stdc++.h>
#define maxn 1000005
using namespace std;
char s[maxn],t[maxn];
int n,pre[maxn],wh[30],from[maxn],you[30];
vector <int> v[maxn];
int b[maxn];
int lowbit(int x){return x&(-x);}
int add(int x){
	//cout<<x<<endl;
	for(int i=x;i<=n;i+=lowbit(i))b[i]++;
}
int query(int x){
	int ret=0;
	for(int i=x;i;i-=lowbit(i))ret+=b[i];
//	cout<<x<<" "<<ret<<endl;
	return ret;
}
int main(){
//	freopen("game9.in","r",stdin);
//	froepen("game.out","w",stdout);
	scanf("%d",&n);
	scanf("%s",s+1);scanf("%s",t+1);
	for(int i=1;i<=n;i++){
		pre[i]=wh[s[i]-'a'];
		wh[s[i]-'a']=i;
	}
	int mn=n+1;
	for(int i=n;i>=1;i--){
		int o=wh[t[i]-'a'];
		if(o<=mn && you[t[i]-'a'])continue;
		you[t[i]-'a']=1;
		while((o>mn || o>i) && o!=0)o=pre[o];
		wh[t[i]-'a']=o;
		mn=min(mn,o);
		if(o==0){
			puts("-1");return 0;
		}
		v[o].push_back(i);
	}
	int mx=0;
	for(int i=1;i<=n;i++){
		for(int j=0;j<(int)v[i].size();j++){
			if(v[i][j]<=mx){
			//	cout<<i<<" "<<v[i][j]<<" "<<mx<<endl;
				puts("-1");return 0;
			}
		}
		for(int j=0;j<(int)v[i].size();j++){
			mx=max(mx,v[i][j]);
			if(v[i][j]!=i){
				add(i);
			}
		}
	}
	int ans=0;
	for(int i=1;i<=n;i++){
		for(int j=0;j<(int)v[i].size();j++){
			if(v[i][j]!=i){
				ans=max(ans,query(v[i][j])-query(i-1));
			}
		}
	}
	printf("%d\n",ans);
	return 0;
}