Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int INF = 0x3f3f3f3f;
- const int MAX = 51;
- const int dx[] = {0, 0, -1, 1};
- const int dy[] = {-1, 1, 0, 0};
- const char dir[] = {'L', 'R', 'U', 'D'};
- int n, m, ex, ey, rx, ry;
- bitset<2502> dp[MAX][MAX][MAX];
- bitset<2502> calc[MAX][MAX][MAX];
- char ch[MAX][MAX];
- string str;
- bool valid(int x, int y) {
- return !(x < 0 or x >= n or y < 0 or y >= m or ch[x][y] == '#');
- }
- bool solve(int x, int y, int qtd, int pos) {
- if (x == ex and y == ey) {
- return true;
- }
- if (calc[x][y][pos][qtd]) return dp[x][y][pos][qtd];
- calc[x][y][pos][qtd] = true;
- bool ans = false;
- if (qtd > 0 and pos < (int)str.size()) ans = max(ans, solve(x, y, qtd-1, pos-1));
- for (int k = 0; k < 4; ++k) {
- int nx = x + dx[k];
- int ny = y + dy[k];
- if (pos < (int)str.size() and dir[k] == str[pos]) {
- if (valid(nx, ny)) {
- ans = max(ans, solve(nx, ny, qtd, pos+1));
- } else {
- ans = max(ans, solve(x, y, qtd, pos+1));
- }
- } else {
- if (valid(nx, ny) and qtd > 0) {
- ans = max(ans, solve(nx, ny, qtd-1, pos));
- if (qtd > 1) ans = max(ans, solve(nx, ny, qtd-2, pos+1));
- }
- }
- }
- dp[x][y][pos].set(qtd, ans);
- return ans;
- }
- int main() {
- cin.tie(0)->sync_with_stdio(0);
- cin >> n >> m;
- for (int i = 0; i < n; ++i) {
- for (int j = 0; j < m; ++j) {
- cin >> ch[i][j];
- if (ch[i][j] == 'R') {
- rx = i; ry = j;
- } else if(ch[i][j] == 'E') {
- ex = i; ey = j;
- }
- }
- }
- cin >> str;
- int ans = 0;
- for (int i = 0; i <= n*m; ++i) {
- if (solve(rx, ry, i, 0)) {
- ans = i;
- break;
- }
- }
- cout << ans << '\n';
- }
Add Comment
Please, Sign In to add comment