Alex_tz307

Grupe X - 6.6.10 / pag 178

Sep 22nd, 2020 (edited)
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int di[] = {-1, 0, 1, 0, -1, -1, 1, 1},
  6.           dj[] = {0, 1, 0, -1, -1, 1, -1, 1};
  7.  
  8. int main() {
  9.     ios_base::sync_with_stdio(false);
  10.     cin.tie(nullptr);
  11.     cout.tie(nullptr);
  12.     int N, M;
  13.     cin >> N >> M;
  14.     vector < string > a(N + 1);
  15.     for(int i = 1; i <= N; ++i) {
  16.         cin >> a[i];
  17.         a[i] = '$' + a[i];
  18.     }
  19.     string s;
  20.     cin >> s;
  21.     s = '$' + s;
  22.     int k = s.size() - 1;
  23.     vector < vector < int > > dp(N + 1, vector < int >(M + 1));
  24.     for(int i = 1; i <= N; ++i)
  25.         for(int j = 1; j <= M; ++j)
  26.             if(a[i][j] == s[1])
  27.                 dp[i][j] = 1;
  28.     /* dp[i][j] = nr. de ap. al subsirului din s care incepe la poz. 1 si se termina
  29.     pe poz. coresp. elementului a[i][j] */
  30.     auto inside = [&](int lin, int col) {
  31.         return lin > 0 && col > 0 && lin <= N && col <= M;
  32.     };
  33.     for(int l = 2; l <= k; ++l)
  34.         for(int i = 1; i <= N; ++i)
  35.             for(int j = 1; j <= M; ++j)
  36.                 if(a[i][j] == s[l])
  37.                     for(int d = 0; d < 8; ++d) {
  38.                         int lin = i + di[d],
  39.                             col = j + dj[d];
  40.                         if(inside(lin, col) && a[lin][col] == s[l - 1])
  41.                             dp[i][j] += dp[lin][col];
  42.                     }
  43.     int ans = 0;
  44.     for(int i = 1; i <= N; ++i)
  45.         for(int j = 1; j <= M; ++j)
  46.             if(a[i][j] == s[k])
  47.                 ans += dp[i][j];
  48.     cout << ans;
  49. }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment