#define _USE_MATH_DEFINES #include using namespace std; #define FOR(i,m,n) for(int i=(m);i<(n);++i) #define REP(i,n) FOR(i,0,n) #define ALL(v) (v).begin(),(v).end() using ll = long long; constexpr int INF = 0x3f3f3f3f; constexpr long long LINF = 0x3f3f3f3f3f3f3f3fLL; constexpr double EPS = 1e-8; constexpr int MOD = 1000000007; // constexpr int MOD = 998244353; constexpr int DY[]{1, 0, -1, 0}, DX[]{0, -1, 0, 1}; constexpr int DY8[]{1, 1, 0, -1, -1, -1, 0, 1}, DX8[]{0, -1, -1, -1, 0, 1, 1, 1}; template inline bool chmax(T &a, U b) { return a < b ? (a = b, true) : false; } template inline bool chmin(T &a, U b) { return a > b ? (a = b, true) : false; } struct IOSetup { IOSetup() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); std::cout << fixed << setprecision(20); } } iosetup; template std::vector> run_length_encoding(const U &s) { int n = s.size(); std::vector> res; T now = s[0]; int cnt = 1; for (int i = 1; i < n; ++i) { if (s[i] != now) { res.emplace_back(now, cnt); cnt = 0; } now = s[i]; ++cnt; } res.emplace_back(now, cnt); return res; } int solve(int n, const string &s, const vector> &t) { if (s.front() != t.front().first) return INF; const int m = t.size(); auto rle = run_length_encoding(s); int pt = 0, ps = 0, ans = 0; while (true) { while (ps < rle.size() && pt < m && t[pt] == rle[ps]) ++ps, ++pt; if (rle.size() > ps + 1) rle.resize(ps + 1); if (pt == m) return ps == rle.size() ? ans : ans + 1; ++ans; if (ps == rle.size()) { --ps, --pt; if (ps == 0) return INF; } if (t[pt].second % 2 == 1) return INF; while (rle[ps].second < t[pt].second) { rle[ps].second = min(rle[ps].second * 2, t[pt].second); if (rle[ps].second < t[pt].second) ++ans; } rle[ps].second = t[pt].second; ++ps; ++pt; for (int i = ps - 2; i >= 0; --i) { rle.emplace_back(rle[i]); if (pt == m || rle.back() != t[pt]) break; ++ps; ++pt; } // cout << ps << ' ' << pt << " : " << ans << '\n'; // REP(i, rle.size()) cout << '{' << rle[i].first << ',' << rle[i].second << '}' << " \n"[i + 1 == rle.size()]; } assert(false); return INF; } int main() { int n, m; string s, t; cin >> n >> m >> s >> t; if (m % 2 == 1 || !equal(ALL(t), t.rbegin())) { cout << "-1\n"; return 0; } auto rle = run_length_encoding(t); int ans = solve(n, s, rle); reverse(ALL(s)); chmin(ans, solve(n, s, rle)); cout << (ans == INF ? -1 : ans) << '\n'; return 0; }