#include <vector>
#include <math.h>
#include <iostream>

using namespace std;

vector<int> cudoodfunkcije(char* A,char* B,int Al,int Bl)
{
    vector<int> res;
    for(int i=-Bl+1;i<Al+Bl-2;i++)
    {
        for(int j=max(i,0);j<Al && j<Bl+i;j++)
        {
            if(A[j+1]!=B[j-i+1])
            {
                goto end;
            }
        }
        res.push_back(i);
        //cout<<i<<endl;
        end:;
    }
    return res;
}

int analiziraj(vector<int> in,char* s,int nt,char* A,char* B,int Al,int Bl)
{
    int minneg=-Al;
    int maxover=Al;
    int countinternal=0;
    for(int i=0;i<in.size();i++)
    {
        if(in[i]<0 && in[i]>minneg){minneg=in[i];}
        else if(in[i]>=0 && in[i]<=nt){countinternal++;}
        else if(in[i]>nt && in[i]<maxover){maxover=in[i];}
    }
    //cout<<minneg<<" "<<maxover<<" "<<countinternal<<endl;
    if(countinternal>1){return -1;}
    else if(countinternal==1)
    {
        for(int i=0;i<Al;i++)
        {
            s[i+1]=A[i+1];
        }
        return Al;
    }
    if((Bl+minneg)>(Al-maxover))
    {
        for(int i=0;i<-minneg;i++)
        {
            s[i+1]=B[i+1];
        }
        for(int i=-minneg;i<Al-minneg;i++)
        {
            s[i+1]=A[i+minneg+1];
        }
        return Al-minneg;
    }
    else
    {
        for(int i=0;i<Al;i++)
        {
            s[i+1]=A[i+1];
        }
        for(int i=0;i<Bl-(Al-maxover);i++)
        {
            s[i+1+Al]=B[i+1+(Al-maxover)];
        }
        return Bl+maxover;
    }
}

int Resi(int N, int K, int* L, char** A, char* S) {

    vector<int> res;
    int out;
	if(N==2)
    {
        if(L[1]>L[2])
        {
            res = cudoodfunkcije(A[1],A[2],L[1],L[2]);
            out = analiziraj(res,S,abs(L[2]-L[1]),A[1],A[2],L[1],L[2]);
        }
        else
        {
            res = cudoodfunkcije(A[2],A[1],L[2],L[1]);
            out = analiziraj(res,S,abs(L[2]-L[1]),A[2],A[1],L[2],L[1]);
        }
    }

	return out;
}