2 solutions

  • 0
    @ 2026-10-27 8:36:44

    • 0
      @ 2026-10-27 8:35:51
      #include <bits/stdc++.h>
      using namespace std;
      #define FIO(s)                    \
          freopen(s ".in", "r", stdin); \
          freopen(s ".out", "w", stdout);
      template <typename T>
      void chkmn(T &x, T y) { x = min(x, y); }
      template <typename T>
      void chkmx(T &x, T y) { x = max(x, y); }
      const int inf = 1e9;
      void solve()
      {
          int n, m;
          string s, t;
          cin >> n >> m >> s >> t;
          const string str = s + '#' + t;
          const int N = n + 1 + m;
          vector<int> z(N);
          for (int i = 1, l = 0, r = 0; i < N; i++)
          {
              if (i <= r && z[i - l] < r - i + 1)
                  z[i] = z[i - l];
              else
              {
                  z[i] = max(0, r - i + 1);
                  while (i + z[i] < N && str[z[i]] == str[i + z[i]])
                      z[i]++;
              }
              if (i + z[i] - 1 > r)
                  l = i, r = i + z[i] - 1;
          }
          vector<int> f(m + 1, inf);
          f[0] = 0;
          int r = 0;
          for (int i = 0; i < m; i++)
          {
              for (int j = r + 1; j <= i + z[n + 1 + i]; j++)
                  chkmn(f[j], f[i] + 1);
              chkmx(r, i + z[n + 1 + i]);
          }
          cout << (f[m] == inf ? -1 : f[m]) << '\n';
      }
      int main()
      {
          FIO("string");
          ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
          int t;
          cin >> t >> t;
          while (t--)
              solve();
          return 0;
      }
      
      • 1

      Information

      ID
      3153
      Time
      1000ms
      Memory
      1024MiB
      Difficulty
      10
      Tags
      (None)
      # Submissions
      1
      Accepted
      1
      Uploaded By