Problem:
Problem C:
Dungeon Quest II
The cave, called "Mass of Darkness", had been a agitating point of the evil, but the devil king
and all of his soldiers were destroyed by the hero and the peace is there now.
One day, however, the hero was worrying about the rebirth of the devil king, so he decided to
ask security agency to patrol inside the cave.
The information of the cave is as follows:
The cave is represented as a two-dimensional field which consists of rectangular grid of
      cells.
The cave has
R
×
C
cells where
R
is the number of rows and
C
is the number of columns.
Some of the cells in the cave contains a trap, and those who enter the trapping cell will
      lose his hit points.
The type of traps varies widely: some of them reduce hit points seriously, and others give
      less damage.
The following is how the security agent patrols:
The agent will start his patrol from upper left corner of the cave.
- There are no traps at the upper left corner of the cave.
The agent will patrol by tracing the steps which are specified by the hero.
- The steps will be provided such that the agent never go outside of the cave during
             his patrol.
The agent will bring potions to regain his hit point during his patrol.
The agent can use potions just before entering the cell where he is going to step in.
The type of potions also varies widely: some of them recover hit points so much, and
      others are less effective.
- Note that agent’s hit point can be recovered up to
HP
max
which means his maximum
             hit point and is specified by the input data.
The agent can use more than one type of potion at once.
If the agent's hit point becomes less than or equal to 0, he will die.
Your task is to write a program to check whether the agent can finish his patrol without dying.
Input
The input is a sequence of datasets. Each dataset is given in the following format:
HP
init
HP
max
R C
a
1,1
a
1,2
...
a
1,
C
a
2,1
a
2,2
...
a
2,
C
.
.
.
a
R
,1
a
R
,2
...
a
R
,
C
T
[
A-Z
]
d
1
[
A-Z
]
d
2
.
.
.
[
A-Z
]
d
T
S
[
UDLR
]
n
1
[
UDLR
]
n
2
.
.
.
[
UDLR
]
n
S
P
p
1
p
2
.
.
.
p
P
The first line of a dataset contains two integers
HP
init
and
HP
max
(0 <
HP
init
≤
HP
max
≤ 1000),
meaning the agent's initial hit point and the agent’s maximum hit point respectively.
The next line consists of
R
and
C
(1 ≤
R
,
C
≤ 100). Then,
R
lines which made of
C
characters
representing the information of the cave follow. The character
a
i,j
means there are the trap of
type
a
i,j
in
i
-th row and
j
-th column, and the type of trap is denoted as an uppercase alphabetic
character [
A-Z
].
The next line contains an integer
T
, which means how many type of traps to be described.
The following
T
lines contains a uppercase character [
A-Z
] and an integer
d
i
(0 ≤
d
i
≤ 1000),
representing the type of trap and the amount of damage it gives.
The next line contains an integer
S
(0 ≤
S
≤ 1000) representing the number of sequences which
the hero specified as the agent's patrol route. The
...(truncated)

Submitted solutions:

code_snippet: #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define MAXN 310
#define MAXM 5010
#define FI first
#define SE second
#define MP(x,y) make_pair(x,y)
const int INF =1000000007;
char ma[MAXN][MAXN];
int sd[MAXM],len[MAXM],pot[MAXN];
int cost[MAXN],dp[MAXM];
const int dis[4][2]={{-1,0},{0,1},{1,0},{0,-1}};
int main()
{
    //freopen("J:\\Mydocument\\Code\\input.txt","r",stdin);
    int hinit,hmax,ss,sp,st,sr,sc;
    while(scanf("%d%d",&hinit,&hmax)&&(hinit||hmax))
    {
        scanf("%d%d",&sr,&sc);
        for(int i=0;i<sr;++i)    scanf("%s",ma[i]);
        scanf("%d",&st);
        memset(cost,0,sizeof(cost));
        for(int i=0;i<st;++i)
        {
            char tmp[10];
            scanf("%s",tmp);
            scanf("%d",&cost[tmp[0]]);
        }
        scanf("%d",&ss);
        for(int i=0;i<ss;++i)
        {
            char tmp[10];
            scanf("%s%d",tmp,&len[i]);
            if(tmp[0]=='U') sd[i]=0;
            else    if(tmp[0]=='R') sd[i]=1;
            else    if(tmp[0]=='D') sd[i]=2;
            else    if(tmp[0]=='L') sd[i]=3;
        }
        scanf("%d",&sp);
        for(int i=0;i<sp;++i)    scanf("%d",&pot[i]);
        memset(dp,0,sizeof(dp));
        dp[0]=hinit;
        for(int i=0,x=0,y=0,top=(1<<sp);i<ss;++i)
            while(len[i]--)
            {
                x+=dis[sd[i]][0],y+=dis[sd[i]][1];
                for(int j=0;j<top;++j)
                    for(int k=0;dp[j]>0&&k<sp;++k)
                        if((j&(1<<k))==0)
                            dp[j|(1<<k)]=min(hmax,max(dp[j|(1<<k)],dp[j]+pot[k]));
                for(int j=0;j<top;++j)
                    dp[j]-=cost[ma[x][y]];
            }
        bool flag=false;
        for(int j=(1<<sp)-1;j>=0;--j)   flag|=dp[j]>0;
        printf("%s\n",flag?"YES":"NO");
    }
    return 0;
}
accuracy: 1
time_ms: 1760
memory_kb: 2808
final_rank: 6

code_snippet: #include <iostream>
#include <iomanip>
#include <cassert>
#include <vector>
#include <algorithm>
#include <utility>
#include <numeric>
#include <tuple>
// #include "Src/Number/IntegerDivision.hpp"
// #include "Src/Utility/BinarySearch.hpp"
// #include "Src/Sequence/CompressedSequence.hpp"
// #include "Src/Sequence/RunLengthEncoding.hpp"
// #include "Src/Algebra/Group/AdditiveGroup.hpp"
// #include "Src/DataStructure/FenwickTree/FenwickTree.hpp"
// using namespace zawa;
// #include "atcoder/modint"
// using mint = atcoder::modint998244353;
bool solve() {
    int HPINIT, HPMAX;
    std::cin >> HPINIT >> HPMAX;
    if (HPINIT == 0 and HPMAX == 0) return false;
    int R, C;
    std::cin >> R >> C;
    std::vector<std::string> G(R);
    for(auto& g : G) std::cin >> g;
    int T;
    std::cin >> T;
    std::vector<int> TRAP(26);
    for (int i = 0 ; i < T ; i++) {
        char c;
        int d;
        std::cin >> c >> d;
        TRAP[c - 'A'] = d;
    }
    int S;
    std::cin >> S;
    std::vector<std::pair<char, int>> OP(S);
    for (auto& [c, n] : OP) std::cin >> c >> n;
    int P;
    std::cin >> P;
    std::vector<int> POTION(P);
    for (int& p : POTION) std::cin >> p;
    std::vector<int> dp(1 << P);
    dp[(1 << P) - 1] = HPINIT;
    int y = 0, x = 0;
    std::vector<int> recov(1 << P);
    for (int i = 0 ; i < P ; i++) {
        for (int b = 0 ; b < (1 << P) ; b++) if (b & (1 << i)) recov[b] += POTION[i];
    }
    for (auto [c, n] : OP) {
        while (n--) {
            y += (c == 'D' ? 1 : (c == 'U' ? -1 : 0));
            x += (c == 'R' ? 1 : (c == 'L' ? -1 : 0));
            assert(0 <= y and y < R and 0 <= x and x < C);
            const int d = TRAP[G[y][x] - 'A'];
            std::vector<int> next(1 << P);
            for (int b = 0 ; b < (1 << P) ; b++) if (dp[b] > 0) {
                for (int msk = b ; ; msk = (msk - 1) & b) {
                    int hp = std::min(HPMAX, dp[b] + recov[msk]);
                    hp -= d;
                    hp = std::max(0, hp);
                    next[b ^ msk] = std::max(next[b ^ msk], hp);
                    if (msk == 0) break;
                }
            }
            dp = std::move(next);
        }
    }
    for (int b = 0 ; b < (1 << P) ; b++) if (dp[b] > 0) {
        std::cout << "YES\n";
        return true;
    }
    std::cout << "NO\n";
    return true;
}
int main() {
    std::cin.tie(nullptr);
    std::cout.tie(nullptr);
    std::ios::sync_with_stdio(false);
    while (solve()) ;
}
accuracy: 1
time_ms: 5390
memory_kb: 3712
final_rank: 16

code_snippet: // AOJ #2244 Dungeon Quest II
// 2025.2.20

#include <bits/stdc++.h>
using namespace std;
 
const int INF = -1;

struct State { int mask, hp; };

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    
    while(true){
        int HPinit, HPmax;
        cin >> HPinit >> HPmax;
        if(HPinit == 0) break;
        
        int R, C;
        cin >> R >> C;
        vector<string> cave(R);
        for (int i = 0; i < R; i++) cin >> cave[i];
        
        int T;
        cin >> T;
        int trapDamage[26] = {0};
        for (int i = 0; i < T; i++){
            char ch; int d;
            cin >> ch >> d;
            trapDamage[ch-'A'] = d;
        }
        
        int S;
        cin >> S;
        vector<char> dir(S);
        vector<int> nstep(S);
        for (int i = 0; i < S; i++) cin >> dir[i] >> nstep[i];

        vector<int> patrol;
        int r = 0, c = 0;
        for (int i = 0; i < S; i++){
            for (int j = 0; j < nstep[i]; j++){
                if(dir[i]=='U') r--;
                else if(dir[i]=='D') r++;
                else if(dir[i]=='L') c--;
                else if(dir[i]=='R') c++;
                int d = trapDamage[cave[r][c]-'A'];
                patrol.push_back(d);
            }
        }
        int totalSteps = patrol.size();
        
        int P;
        cin >> P;
        vector<int> potions(P);
        for (int i = 0; i < P; i++) cin >> potions[i];

        int fullMask = (1 << P) - 1;
        
        vector<int> dp(1 << P, INF), nextdp(1 << P, INF);
        dp[0] = HPinit;
        
        for (int step = 0; step < totalSteps; step++){
            int d = patrol[step];
            fill(nextdp.begin(), nextdp.end(), INF);
            for (int mask = 0; mask < (1 << P); mask++){
                if(dp[mask] == INF) continue;
                int curHP = dp[mask];
                if(curHP > d){
                    nextdp[mask] = max(nextdp[mask], curHP - d);
                }
                if(curHP <= d && P > 0){
                    vector<int> visited(1 << P, INF);
                    queue<State> que;
                    visited[mask] = curHP;
                    que.push({mask, curHP});
                    while(!que.empty()){
                        State st = que.front();
                        que.pop();
                        int used = st.mask;
                        int hp_now = st.hp;
                        int avail = fullMask ^ used;
                        for (int i = 0; i < P; i++){
                            if(avail & (1 << i)){
                                int newMask = used | (1 << i);
                                int newHP = hp_now + potions[i];
                                if(newHP > HPmax) newHP = HPmax;
                                if(newHP > visited[newMask]){
                                    visited[newMask] = newHP;
                                    if(newHP > d)
                                        nextdp[newMask] = max(nextdp[newMask], newHP - d);
                                    else
                                        que.push({newMask, newHP});
                                }
                            }
                        }
                    }
                }
            }
            dp.swap(nextdp);
        }
        bool possible = false;
        for (int mask = 0; mask < (1 << P); mask++){
            if(dp[mask] > 0) { possible = true; break; }
        }
        cout << (possible ? "YES" : "NO") << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 180
memory_kb: 3452
final_rank: 2

code_snippet: // AOJ #2244 Dungeon Quest II
// 2025.2.20
 
#include <bits/stdc++.h>
using namespace std;
 
const int INF = -1;
 
 
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    
    while(true){
        int HPinit, HPmax;
        cin >> HPinit >> HPmax;
        if(HPinit==0) break;
        
        int R, C;
        cin >> R >> C;
        vector<string> cave(R);
        for (int i = 0; i < R; i++) cin >> cave[i];
        
        int T;
        cin >> T;
        int trapDamageMapping[26];
        for (int i = 0; i < 26; i++) trapDamageMapping[i] = 0;
        for (int i = 0; i < T; i++){
            char ch;
            int d;
            cin >> ch >> d;
            trapDamageMapping[ch-'A'] = d;
        }
        
        int S;
        cin >> S;
        vector<char> directions;
        vector<int> steps;
        for (int i = 0; i < S; i++){
            char dir;
            int n;
            cin >> dir >> n;
            directions.push_back(dir);
            steps.push_back(n);
        }
        
        vector<int> patrolTrap;
        int r = 0, c = 0;
        for (int i = 0; i < S; i++){
            char d = directions[i];
            int n = steps[i];
            for (int j = 0; j < n; j++){
                if(d=='U') r--;
                else if(d=='D') r++;
                else if(d=='L') c--;
                else if(d=='R') c++;
                char trapType = cave[r][c];
                int damage = trapDamageMapping[trapType-'A'];
                patrolTrap.push_back(damage);
            }
        }
        int totalSteps = patrolTrap.size();
        
        int P;
        cin >> P;
        vector<int> potions(P);
        for (int i = 0; i < P; i++) cin >> potions[i];
        
        if(P==0){
            int hp = HPinit;
            bool survive = true;
            for (int i = 0; i < totalSteps; i++){
                hp -= patrolTrap[i];
                if(hp <= 0){
                    survive = false;
                    break;
                }
            }
            cout << (survive ? "YES" : "NO") << endl;
            continue;
        }
        
        int potionStates = 1 << P;
        vector<int> sumPotions(potionStates, 0);
        for (int mask = 0; mask < potionStates; mask++){
            int sum = 0;
            for (int i = 0; i < P; i++)
                if(mask & (1 << i)) sum += potions[i];
            sumPotions[mask] = sum;
        }
        
        vector<int> dp(potionStates, INF);
        dp[0] = HPinit;
        
        for (int step = 0; step < totalSteps; step++){
            vector<int> nextDP(potionStates, INF);
            int damage = patrolTrap[step];
            for (int mask = 0; mask < potionStates; mask++){
                if(dp[mask] == INF) continue;
                int curHP = dp[mask];
                int available = ((1 << P) - 1) ^ mask;
                for (int sub = available;; sub = (sub-1) & available) {
                    int recovery = sumPotions[sub];
                    int newHP_pre = curHP + recovery;
                    if(newHP_pre > HPmax) newHP_pre = HPmax;
                    int newHP = newHP_pre - damage;
                    if(newHP > 0) {
                        int newMask = mask | sub;
                        nextDP[newMask] = max(nextDP[newMask], newHP);
                    }
                    if(sub == 0) break;
                }
            }
            dp = move(nextDP);
        }
        
        bool possible = false;
        for (int mask = 0; mask < potionStates; mask++){
            if(dp[mask] > 0) { possible = true; break; }
        }
        cout << (possible ? "YES" : "NO") << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 6150
memory_kb: 3472
final_rank: 18

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
 * @brief template
 */

int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1};

int main() {
while(1) {
    int HI, HM;
    cin >> HI >> HM;
    if (HI == 0) return 0;
    int N, M;
    cin >> N >> M;
    vector<string> S(N);
    rep(i,0,N) cin >> S[i];
    vector<vector<int>> A(N,vector<int>(M));
    map<char,int> mp;
    int _;
    cin >> _;
    while(_--) {
        char c;
        int a;
        cin >> c >> a;
        mp[c] = a;
    }
    rep(i,0,N) rep(j,0,M) A[i][j] = mp[S[i][j]];
    vector<int> D;
    int CX = 0, CY = 0;
    cin >> _;
    while(_--) {
        char c;
        int a;
        cin >> c >> a;
        int dir;
        if (c == 'D') dir = 0;
        if (c == 'R') dir = 1;
        if (c == 'U') dir = 2;
        if (c == 'L') dir = 3;
        while(a--) {
            CX += dx[dir], CY += dy[dir];
            D.push_back(A[CX][CY]);
        }
    }
    int K;
    cin >> K;
    vector<int> P(K);
    rep(i,0,K) cin >> P[i];
    int L = D.size();
    vector<vector<int>> DP(L+1,vector<int>(1<<K,0));
    DP[0][0] = HI;
    rep(i,0,L) {
        rep(j,0,1<<K) {
            if (DP[i][j] == 0) continue;
            rep(k,0,K) {
                if (j & (1<<k)) continue;
                chmax(DP[i][j|(1<<k)],min(HM,DP[i][j]+P[k]));
            }
        }
        rep(j,0,1<<K) {
            chmax(DP[i+1][j],DP[i][j]-D[i]);
        }
    }
    bool check = false;
    rep(i,0,1<<K) if (DP[L][i] > 0) check = true;
    cout << (check ? "YES" : "NO") << endl;
}
}
accuracy: 1
time_ms: 1900
memory_kb: 19200
final_rank: 13

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

string solve(int HP_init, int HP_max) {
    int H = in(), W = in();
    vector<string> a = in(H);
    int T = in();
    map<char, int> damage;
    for(int i : rep(T)) {
        char c = in(); int d = in();
        damage[c] = d;
    }
    int S = in();
    vector<char> move;
    for(int i : rep(S)) {
        char d = in(); int n = in();
        for(int _ : rep(n)) move.push_back(d);
    }
    int P = in();
    vector<int> potion = in(P);

    vector<int> dp(1 << P, -1e9); // 使ったポーションの集合 -> 体力の最大値
    dp[0] = HP_init;

    int i = 0, j = 0;
    for(char m : move) {
        if(m == 'U') i--;
        if(m == 'D') i++;
        if(m == 'L') j--;
        if(m == 'R') j++;

        int dmg = damage[a[i][j]];
        vector<int> nt(1 << P, -1e9);
        for(int set : rep(1 << P)) {
            if(0 < dp[set] - dmg) chmax(nt[set], dp[set] - dmg);
            for(int i : rep(P)) if(!(set & (1 << i))) {
                int hp = min(dp[set] + potion[i], HP_max);
                if(0 < hp - dmg) chmax(nt[set  ^ (1 << i)], hp - dmg);
            }
        }
        dp = std::move(nt);
    }

    for(int st : rep(1 << P)) if(0 < dp[st]) return "YES";
    return "NO";
}

int main() {
    while(true) {
        int HP_init = in(), HP_max = in();
        if(make_pair(HP_init, HP_max) == make_pair(0, 0)) return 0;
        print(solve(HP_init, HP_max));
    }
}
accuracy: 1
time_ms: 2930
memory_kb: 3436
final_rank: 9

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rng(i, l, r) for(int i = int(l); i < int(r); i++)
#define rep(i, n) rng(i, 0, n)
#define sz(v) int(v.size())
#define foa(s, v) for(auto& s : v)
#define all(v) v.begin(), v.end()
template <class T>
using V = vector<T>;

template <class T>
bool chmax(T& a, T b) {
	return a < b ? a = b, 1 : 0;
}
template <class T>
bool chmin(T& a, T b) {
	return a > b ? a = b, 1 : 0;
}

#ifdef LOCAL
#define debug(x) cerr << #x << ": " << x << endl
#else
#define debug(x) void(0)
#endif

ostream& operator<<(ostream& os, vector<int> vec) {
	os << "{";
	foa(c, vec) os << c << ", ";
	return os << "}";
}

int start_hp;
bool solve() {
	int max_hp;
	cin >> max_hp;
	debug(start_hp);
	debug(max_hp);
	int h, w;
	cin >> h >> w;
	debug(h);
	debug(w);
	vector<string> grid(h);
	foa(r, grid) cin >> r;

	foa(c, grid) debug(c);

	map<char, int> damages;
	{
		int t;
		cin >> t;
		rep(j, t) {
			char c;
			cin >> c;
			int d;
			cin >> d;
			damages[c] = d;
		}
	}

	map<char, pair<int, int>> command;
	command['U'] = pair(-1, 0);
	command['L'] = pair(0, -1);
	command['D'] = pair(1, 0);
	command['R'] = pair(0, 1);
	vector<pair<char, int>> commands;
	{
		int s;
		cin >> s;
		rep(j, s) {
			char cmd;
			cin >> cmd;
			int n;
			cin >> n;
			commands.emplace_back(cmd, n);
		}
	}

	int potions_num;
	cin >> potions_num;
	vector<int> potions(potions_num);
	foa(c, potions) cin >> c;

	debug(potions_num);

	const int bitmax = 1 << potions_num;
	vector<int> psums(bitmax);
	rep(bits, (bitmax)) rep(j, potions_num) {
		if(bits & (1 << j)) { psums[bits] += potions[j]; }
	}

	foa(p, potions) debug(p);

	vector<int> remain_max(bitmax, 0);
	remain_max.back() = start_hp;

	int x, y;
	x = y = 0;
	for(auto [cmd, repeat] : commands) {
		int dx, dy;
		tie(dx, dy) = command.at(cmd);
		debug(dx);
		debug(dy);

		rep(j, repeat) {
			vector<int> tmp(bitmax, 0);

			x += dx;
			y += dy;

			debug(x);
			debug(y);

			assert(0 <= x && x < h && 0 <= y && y < w);
			int dam = damages.at(grid[x][y]);
			debug(dam);

			rep(bits, bitmax) {
				int pre = remain_max[bits];
				if(pre <= 0) continue;
				for(int use = bits; use >= 0; use--) {
					use &= bits;
					int remain = min(max_hp, pre + psums[use]);
					chmax(tmp[bits - use], remain - dam);
				}
			}

			if(*max_element(all(tmp)) <= 0) return false;
			swap(tmp, remain_max);

			debug(remain_max);
		}
	}
	return true;
}
int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	while(cin >> start_hp && start_hp) cout << (solve() ? "YES" : "NO") << endl;
}
accuracy: 1
time_ms: 5430
memory_kb: 3340
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, s, t) for (int i = (int)(s); i < (int)(t); ++i)
#define revrep(i, t, s) for (int i = (int)(t)-1; i >= (int)(s); --i)
#define all(x) begin(x), end(x)
template <typename T> bool chmax(T& a, const T& b) { return a < b ? (a = b, 1) : 0; }
template <typename T> bool chmin(T& a, const T& b) { return a > b ? (a = b, 1) : 0; }

template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
    for (int i = 0; i < (int) v.size(); ++i) {
        os << v[i];
        if (i < (int) v.size() - 1) os << " ";
    }
    return os;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(15);

    const vector<int> di = {0, 1, 0, -1};
    const vector<int> dj = {1, 0, -1, 0};
    string dir = "RDLU";

    auto get_dir = [&](char d) {
        rep(i,0,4) if (dir[i] == d) return i;
        return -1;
    };

    while (true) {
        int hpinit, hpmax;
        cin >> hpinit >> hpmax;
        if (hpinit == 0) break;
        int R, C;
        cin >> R >> C;
        vector<string> a(R);
        for (auto& x : a) cin >> x;
        int T;
        cin >> T;
        vector<int> damage(26);
        rep(i,0,T) {
            char c;
            int d;
            cin >> c >> d;
            damage[c-'A'] = d;
        }
        int S;
        cin >> S;
        vector<pair<char, int>> moves(S);
        for (auto& x : moves) cin >> x.first >> x.second;
        int P;
        cin >> P;
        vector<int> p(P);
        for (auto& x : p) cin >> x;

        vector<int> dam = {0};
        int i = 0, j = 0;
        for (auto [c, d] : moves) {
            int k = get_dir(c);
            rep(_,0,d) {
                i += di[k];
                j += dj[k];
                dam.push_back(damage[a[i][j]-'A']);
            }
        }

        // cout << dam << endl;

        vector<int> dp(1<<P);
        dp.back() = hpinit;
        for (auto d : dam) {
            revrep(B,(1<<P),0) {
                if (dp[B] == 0) continue;
                rep(i,0,P) {
                    if (B>>i&1) {
                        chmax(dp[B^(1<<i)], min(dp[B] + p[i], hpmax));
                    }
                }
            }
            rep(B,0,(1<<P)) {
                dp[B] = max(dp[B] - d, 0);
            }
        }

        bool ans = false;
        rep(B,0,(1<<P)) {
            if (dp[B] > 0) {
                ans = true;
                break;
            }
        }

        cout << (ans ? "YES" : "NO") << endl;
    }
}
accuracy: 1
time_ms: 1660
memory_kb: 3184
final_rank: 5

code_snippet: #include "bits/stdc++.h"
using namespace std;

typedef string::const_iterator State;
#define eps 1e-8L
#define MAX_MOD 1000000007LL
#define GYAKU 500000004LL
#define MOD 998244353LL
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef long double ld;
#define REP(a, b) for (long long(a) = 0; (a) < (b); ++(a))
#define ALL(x) (x).begin(), (x).end()

#define int long long
int dp[2000][(1 << 12)];
void solve()
{
  int hp_init, hp_max;
  int r, c;
  cin >> hp_init >> hp_max;
  if (hp_init == 0)
    exit(0);
  cin >> r >> c;
  vector<string> inputs;
  REP(i, r)
  {
    string s;
    cin >> s;
    inputs.push_back(s);
  }
  int tea;
  cin >> tea;
  map<char, int> costs;
  REP(i, tea)
  {
    string s;
    int b;
    cin >> s >> b;
    costs[s[0]] = b;
  }
  int moves = 0;
  int x = 0;
  int y = 0;
  cin >> moves;
  vector<int> move_costs;
  REP(i, moves)
  {
    string s;
    int n;
    cin >> s >> n;
    REP(q, n)
    {
      if (s == "D")
      {
        x++;
      }
      else if (s == "U")
      {
        x--;
      }
      else if (s == "R")
      {
        y++;
      }
      else
      {
        y--;
      }
      move_costs.push_back(costs[inputs[x][y]]);
    }
  }
  vector<int> portions;
  int ps;
  cin >> ps;
  REP(i, ps)
  {
    int a;
    cin >> a;
    portions.push_back(a);
  }

  REP(i, move_costs.size() + 1)
  {
    REP(q, (1 << portions.size()))
    {
      dp[i][q] = -1e18;
    }
  }
  dp[0][0] = hp_init;
  REP(i, move_costs.size())
  {
    REP(j, portions.size())
    {
      REP(q, (1 << portions.size()))
      {
        if ((1 << j) & q)
        {
          continue;
        }
        if (dp[i][q] <= 0)
          continue;
        dp[i][q | (1 << j)] = max(dp[i][q | (1 << j)], dp[i][q] + portions[j]);
        dp[i][q | (1 << j)] = min(dp[i][q | (1 << j)], hp_max);
      }
    }
    REP(q, (1 << portions.size()))
    {
      dp[i + 1][q] = dp[i][q] - move_costs[i];
    }
  }
  REP(i, (1 << portions.size()))
  {
    if (dp[move_costs.size()][i] > 0)
    {
      cout << "YES" << endl;
      return;
    }
  }
  cout << "NO" << endl;
}

#undef int

// generated by oj-template v4.7.2
// (https://github.com/online-judge-tools/template-generator)
int main()
{
  // Fasterize input/output script
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cout << fixed << setprecision(10);
  // scanf/printf user should delete this fasterize input/output script

  int t = 10000;
  // cin >> t; // comment out if solving multi testcase
  for (int testCase = 1; testCase <= t; ++testCase)
  {
    solve();
  }
  return 0;
}
accuracy: 1
time_ms: 710
memory_kb: 36184
final_rank: 20

code_snippet: #include <bits/stdc++.h>
using namespace std;

const int INF = 1e9;

void solve(int HP_init, int HP_max) {
    int R, C;
    cin >> R >> C;
    vector<string> cave(R);
    for (auto& s : cave) cin >> s;
    int T;
    cin >> T;
    vector<int> trap(26, 0);
    for (; T--;) {
        char c;
        int d;
        cin >> c >> d;
        trap[c - 'A'] = d;
    }
    int S;
    cin >> S;
    vector<int> path;
    for (int x = 0, y = 0; S--;) {
        char dir;
        int n;
        cin >> dir >> n;
        for (; n--;) {
            if (dir == 'U')
                x--;
            else if (dir == 'D')
                x++;
            else if (dir == 'L')
                y--;
            else
                y++;
            path.emplace_back(trap[cave[x][y] - 'A']);
        }
    }
    int P;
    cin >> P;
    vector<int> p(P);
    for (int& x : p) cin >> x;

    int N = path.size();
    vector<vector<int>> dp(N + 1, vector<int>(1 << P, -INF));
    dp[0][0] = HP_init;
    for (int i = 0; i < N; i++) {
        for (int mask = 0; mask < (1 << P); mask++) {
            int val = dp[i][mask];
            if (val < 0) continue;
            for (int j = 0; j < P; j++) {
                if (mask >> j & 1) continue;
                dp[i][mask | 1 << j] = max(dp[i][mask | 1 << j], min(HP_max, val + p[j]));
            }
            if (val > path[i]) dp[i + 1][mask] = max(dp[i + 1][mask], val - path[i]);
        }
    }

    cout << (dp[N][(1 << P) - 1] > 0 ? "YES" : "NO") << '\n';
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int HP_init, HP_max;
    while (cin >> HP_init >> HP_max, HP_init) solve(HP_init, HP_max);
    return 0;
}
accuracy: 1
time_ms: 1960
memory_kb: 19112
final_rank: 14

code_snippet: #define LOCAL
#include <bits/stdc++.h>
using namespace std;
#pragma region Macros
typedef long long ll;
typedef __int128_t i128;
typedef unsigned int uint;
typedef unsigned long long ull;
#define ALL(x) (x).begin(), (x).end()

template <typename T> istream& operator>>(istream& is, vector<T>& v) {
    for (T& x : v) is >> x;
    return is;
}
template <typename T> ostream& operator<<(ostream& os, const vector<T>& v) {
    for (int i = 0; i < (int)v.size(); i++) {
        os << v[i] << (i + 1 == (int)v.size() ? "" : " ");
    }
    return os;
}
template <typename T, typename U> ostream& operator<<(ostream& os, const pair<T, U>& p) {
    os << '(' << p.first << ',' << p.second << ')';
    return os;
}
template <typename T, typename U> ostream& operator<<(ostream& os, const map<T, U>& m) {
    os << '{';
    for (auto itr = m.begin(); itr != m.end();) {
        os << '(' << itr->first << ',' << itr->second << ')';
        if (++itr != m.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T, typename U> ostream& operator<<(ostream& os, const unordered_map<T, U>& m) {
    os << '{';
    for (auto itr = m.begin(); itr != m.end();) {
        os << '(' << itr->first << ',' << itr->second << ')';
        if (++itr != m.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T> ostream& operator<<(ostream& os, const set<T>& s) {
    os << '{';
    for (auto itr = s.begin(); itr != s.end();) {
        os << *itr;
        if (++itr != s.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T> ostream& operator<<(ostream& os, const multiset<T>& s) {
    os << '{';
    for (auto itr = s.begin(); itr != s.end();) {
        os << *itr;
        if (++itr != s.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T> ostream& operator<<(ostream& os, const unordered_set<T>& s) {
    os << '{';
    for (auto itr = s.begin(); itr != s.end();) {
        os << *itr;
        if (++itr != s.end()) os << ',';
    }
    os << '}';
    return os;
}
template <typename T> ostream& operator<<(ostream& os, const deque<T>& v) {
    for (int i = 0; i < (int)v.size(); i++) {
        os << v[i] << (i + 1 == (int)v.size() ? "" : " ");
    }
    return os;
}

template <int i, typename T> void print_tuple(ostream&, const T&) {}
template <int i, typename T, typename H, class... Args> void print_tuple(ostream& os, const T& t) {
    if (i) os << ',';
    os << get<i>(t);
    print_tuple<i + 1, T, Args...>(os, t);
}
template <typename... Args> ostream& operator<<(ostream& os, const tuple<Args...>& t) {
    os << '{';
    print_tuple<0, tuple<Args...>, Args...>(os, t);
    return os << '}';
}

void debug_out() { cerr << '\n'; }
template <class Head, class... Tail> void debug_out(Head&& head, Tail&&... tail) {
    cerr << head;
    if (sizeof...(Tail) > 0) cerr << ", ";
    debug_out(move(tail)...);
}
#ifdef LOCAL
#define debug(...)                                                                   \
    cerr << " ";                                                                     \
    cerr << #__VA_ARGS__ << " :[" << __LINE__ << ":" << __FUNCTION__ << "]" << '\n'; \
    cerr << " ";                                                                     \
    debug_out(__VA_ARGS__)
#else
#define debug(...) 42
#endif

template <typename T> T gcd(T x, T y) { return y != 0 ? gcd(y, x % y) : x; }
template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; }

int topbit(signed t) { return t == 0 ? -1 : 31 - __builtin_clz(t); }
int topbit(long long t) { return t == 0 ? -1 : 63 - __builtin_clzll(t); }
int botbit(signed a) { return a == 0 ? 32 : __builtin_ctz(a); }
int botbit(long long a) { return a == 0 ? 64 : __builtin_ctzll(a); }
int popcount(signed t) { return __builtin_popcount(t); }
int popcount(long long t) { return __builtin_popcountll(t); }
bool ispow2(int i) { return i && (i & -i) == i; }

template <class T> T ceil(T x, T y) {
    assert(y >= 1);
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <class T> T floor(T x, T y) {
    assert(y >= 1);
    return (x > 0 ? x / y : (x - y + 1) / y);
}

template <class T1, class T2> inline bool chmin(T1& a, T2 b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template <class T1, class T2> inline bool chmax(T1& a, T2 b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
#pragma endregion

const int INF = 1e9;
const long long IINF = 1e18;
const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
const long long MOD = 1000000007;
// const long long MOD = 998244353;

void solve(int HP_init, int HP_max) {
    int R, C;
    cin >> R >> C;
    vector<string> cave(R);
    for (auto& s : cave) cin >> s;
    int T;
    cin >> T;
    vector<int> trap(26, 0);
    for (; T--;) {
        char c;
        int d;
        cin >> c >> d;
        trap[c - 'A'] = d;
    }
    int S;
    cin >> S;
    vector<int> path;
    for (int x = 0, y = 0; S--;) {
        char dir;
        int n;
        cin >> dir >> n;
        for (; n--;) {
            if (dir == 'U')
                x--;
            else if (dir == 'D')
                x++;
            else if (dir == 'L')
                y--;
            else
                y++;
            path.emplace_back(trap[cave[x][y] - 'A']);
        }
    }
    int P;
    cin >> P;
    vector<int> p(P);
    for (int& x : p) cin >> x;

    int N = path.size();
    vector<vector<int>> dp(N + 1, vector<int>(1 << P, -INF));
    dp[0][0] = HP_init;
    for (int i = 0; i < N; i++) {
        for (int mask = 0; mask < (1 << P); mask++) {
            int val = dp[i][mask];
            if (val < 0) continue;
            for (int j = 0; j < P; j++) {
                if (mask >> j & 1) continue;
                dp[i][mask | 1 << j] = max(dp[i][mask | 1 << j], min(HP_max, val + p[j]));
            }
            if (val > path[i]) dp[i + 1][mask] = max(dp[i + 1][mask], val - path[i]);
        }
    }

    cout << (dp[N][(1 << P) - 1] > 0 ? "YES" : "NO") << '\n';
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int HP_init, HP_max;
    while (cin >> HP_init >> HP_max, HP_init) solve(HP_init, HP_max);
    return 0;
}
accuracy: 1
time_ms: 1790
memory_kb: 19148
final_rank: 12

code_snippet: #pragma GCC ta g("avx2")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#define DEBUG
#ifdef DEBUG
template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << '(' << p.first << ',' << p.second << ')';
    return os;
}
template <class T> ostream &operator<<(ostream &os, const vector<T> &v) {
    os << '{';
    for(int i = 0; i < (int)v.size(); i++) {
        if(i) { os << ','; }
        os << v[i];
    }
    os << '}';
    return os;
}
void debugg() { cerr << endl; }
template <class T, class... Args>
void debugg(const T &x, const Args &... args) {
    cerr << " " << x;
    debugg(args...);
}
#define debug(...)                                                             \
    cerr << __LINE__ << " [" << #__VA_ARGS__ << "]: ", debugg(__VA_ARGS__)
#define dump(x) cerr << __LINE__ << " " << #x << " = " << (x) << endl
#else
#define debug(...) (void(0))
#define dump(x) (void(0))
#endif
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef pair<ll,ll> P;
typedef pair<int,int> pii;
typedef vector<P> vpl;
typedef tuple<ll,ll,ll> tapu;
#define rep(i,n) for(int i=0; i<(n); i++)
#define REP(i,a,b) for(int i=(a); i<(b); i++)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
const int inf = (1<<30)-1;
const ll linf = 1LL<<61;
const int MAX = 510000;
int dy[8] = {0,1,0,-1,1,-1,-1,1};
int dx[8] = {-1,0,1,0,1,-1,1,-1};
const double pi = acos(-1);
const double eps = 1e-7;
template<typename T1,typename T2> inline bool chmin(T1 &a,T2 b){
	if(a>b){
		a = b; return true;
	}
	else return false;
}
template<typename T1,typename T2> inline bool chmax(T1 &a,T2 b){
	if(a<b){
		a = b; return true;
	}
	else return false;
}
template<typename T> inline void print(T &a){
    int sz = a.size();
    for(auto itr = a.begin(); itr != a.end(); itr++){
		cout << *itr;
        sz--;
        if(sz) cout << " ";
	}
    cout << "\n";
}
template<typename T1,typename T2> inline void print2(T1 a, T2 b){
	cout << a << " " << b << "\n";
}
template<typename T1,typename T2,typename T3> inline void print3(T1 a, T2 b, T3 c){
	cout << a << " " << b << " " << c << "\n";
}
void mark() {cout << "#" << "\n";}
ll pcount(ll x) {return __builtin_popcountll(x);}
//#include <atcoder/maxflow>
//using namespace atcoder;
//const int mod = 1e9 + 7;
const int mod = 998244353;

int main(){
    while(1){
        int fi,m; cin >> fi >> m;
        if(!fi) break;
        int r,c; cin >> r >> c;
        vs s(r); rep(i,r) cin >> s[i];
        vl d(26);
        int t; cin >> t;
        rep(i,t){
            char c; int D; cin >> c >> D;
            d[c-'A'] = D;
        }
        int n; cin >> n;
        vl dir(n), a(n);
        string di = "LDRU";
        rep(i,n){
            char c;
            cin >> c >> a[i];
            rep(j,4) if(di[j] == c) dir[i] = j;
        }
        int k; cin >> k;
        vector<int> p(k); rep(i,k) cin >> p[i];
        vector<int> dp(1<<k,0);
        dp[0] = fi;
        int y = 0, x = 0;
        rep(i,n){
            rep(j,a[i]){
                y += dy[dir[i]];
                x += dx[dir[i]];
                int damage = d[s[y][x]-'A'];
                rep(l,k){
                    rep(bit,1<<k){
                        if(dp[bit] <= 0) continue;
                        if(bit>>l&1^1) chmax(dp[bit|(1<<l)], min(m, dp[bit] + p[l]));
                    }
                }
                rep(bit,1<<k) dp[bit] -= damage;
            }
        }
        bool yes = false;
        rep(bit,1<<k) if(dp[bit] > 0) yes = true;
        if(yes) cout << "YES\n";
        else cout << "NO\n";
    }
}
accuracy: 1
time_ms: 620
memory_kb: 3464
final_rank: 3

code_snippet: #pragma GCC optimize("Ofast")
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <ctime>
#include <assert.h>
#include <chrono>
#include <random>
#include <numeric>
#include <set>
#include <deque>
#include <stack>
#include <sstream>
#include <utility>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    ll cur,H;
    while(cin >> cur >> H,H){
        int h,w; cin >> h >> w;
        vector<string> s(h);
        for(int i=0;i<h;i++){
            cin >> s[i];
        }
        vector<ll> cost(26);
        int m; cin >> m;
        for(int i=0;i<m;i++){
            char c; cin >> c;
            cin >> cost[c-'A'];
        }
        vector<ll> v;
        int x=0,y=0;
        cin >> m;
        for(int i=0;i<m;i++){
            char c; cin >> c;
            int d; cin >> d;
            for(int j=0;j<d;j++){
                if(c=='D')x++;
                else if(c=='U')x--;
                else if(c=='R')y++;
                else y--;
                v.push_back(cost[s[x][y]-'A']);
            }
        }
        cin >> m;
        vector<int> p(m);
        for(int i=0;i<m;i++){
            cin >> p[i];
        }
        vector<ll> dp(1<<m);
        dp[0]=cur;
        for(int i:v){
            for(int j=0;j<(1<<m);j++){
                if(dp[j]<=0)continue;
                for(int k=0;k<m;k++){
                    if((1<<k)&j)continue;
                    dp[j|(1<<k)]=max(dp[j|(1<<k)],min(H,dp[j]+p[k]));
                }
            }
            for(int j=0;j<(1<<m);j++){
                dp[j]-=i;
            }
        }
        if(dp.back()>0){
            printf("YES\n");
        }
        else{
            printf("NO\n");
        }
    }
}
accuracy: 1
time_ms: 1940
memory_kb: 3400
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll = long long;
using PII = pair<ll, ll>;

#define FOR(i, a, n) for (ll i = (ll)a; i < (ll)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define ALL(x) x.begin(), x.end()
#define POPCOUNT(x) __builtin_popcount(x)
template <typename T> void chmin(T &a, const T &b) { a = min(a, b); }
template <typename T> void chmax(T &a, const T &b) { a = max(a, b); }

const ll INF = 1LL << 60;

struct FastIO {
    FastIO() {
        cin.tie(0);
        ios::sync_with_stdio(0);
    }
} fastiofastio;

int dp[1001][1 << 12];
int d[26];
char a[100][101];

int main() {
    while (1) {
        int HP, HPmax;
        cin >> HP >> HPmax;
        if (HP == 0)
            break;
        int R, C;
        cin >> R >> C;
        for (int i = 0; i < R; i++) {
            cin >> a[i];
        }
        int T;
        cin >> T;
        for (int i = 0; i < T; i++) {
            string s;
            cin >> s;
            cin >> d[s[0] - 'A'];
        }
        int S;
        cin >> S;
        vector<string> route;
        for (int i = 0; i < S; i++) {
            string dir;
            int n;
            cin >> dir >> n;
            for (int j = 0; j < n; j++)
                route.push_back(dir);
        }
        int P;
        cin >> P;
        vector<int> p(P);
        for (int i = 0; i < P; i++)
            cin >> p[i];
        memset(dp, 0, sizeof(dp));
        dp[0][0] = HP;
        int x = 0, y = 0;
        for (int i = 0; i < route.size(); i++) {
            const string &dir = route[i];
            if (dir == "U")
                y--;
            else if (dir == "D")
                y++;
            else if (dir == "R")
                x++;
            else
                x--;
            int damage = d[a[y][x] - 'A'];
            for (int j = 0; j < (1 << P); j++) {
                if (dp[i][j] == 0)
                    continue;
                if (dp[i][j] > damage)
                    dp[i + 1][j] = max(dp[i + 1][j], dp[i][j] - damage);
                for (int k = 0; k < P; k++) {
                    if (j & (1 << k))
                        continue;
                    int new_HP = min(dp[i][j] + p[k], HPmax);
                    if (new_HP > damage)
                        dp[i + 1][j | (1 << k)] =
                            max(dp[i + 1][j | (1 << k)], new_HP - damage);
                }
            }
        }
        int ans = 0;
        for (int i = 0; i < (1 << P); i++)
            ans = max(ans, dp[route.size()][i]);
        if (ans == 0)
            cout << "NO" << endl;
        else
            cout << "YES" << endl;
    }
}
accuracy: 1
time_ms: 1710
memory_kb: 19392
final_rank: 11

code_snippet: #include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <tuple>
#include <map>

const std::string way = "UDLR";
const std::vector<std::pair<int, int>>
    dxys{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

std::vector<int> parse() {
    int h, w;
    std::cin >> h >> w;

    std::vector<std::string> ss(h);
    for (auto& s : ss) std::cin >> s;

    std::map<char, int> ds;
    {
        int n;
        std::cin >> n;
        while (n--) {
            char c;
            int d;
            std::cin >> c >> d;
            ds[c] = d;
        }
    }

    std::vector<int> ret;
    int x = 0, y = 0;

    int n;
    std::cin >> n;
    while (n--) {
        char c;
        std::cin >> c;

        int dx, dy;
        for (int i = 0; i < 4; ++i) {
            if (c == way[i]) std::tie(dx, dy) = dxys[i];
        }

        int k;
        std::cin >> k;
        while (k--) {
            x += dx, y += dy;
            ret.push_back(ds[ss[x][y]]);
        }
    }

    return ret;
}

bool solve() {
    int sp, mp;
    std::cin >> sp >> mp;
    if (sp == 0) return false;

    auto ds = parse();

    int n;
    std::cin >> n;
    std::vector<int> ps(n);
    for (auto& p : ps) std::cin >> p;

    std::vector<int> dp(1 << n, 0);
    dp[0] = sp;

    for (auto d : ds) {
        for (int i = 0; i < n; ++i) {
            for (int b = 0; b < (1 << n); ++b) {
                if (((b >> i) & 1) || dp[b] <= 0) continue;
                dp[b | (1 << i)] = std::max(dp[b | (1 << i)],
                                            std::min(mp, dp[b] + ps[i]));
            }
        }

        for (int b = 0; b < (1 << n); ++b) dp[b] -= d;
    }

    auto ans = std::any_of(dp.begin(), dp.end(),
                           [](auto x) { return x > 0; });

    std::cout << (ans ? "YES" : "NO") << "\n";
    return true;
}

int main() {
    std::cin.tie(nullptr);
    std::ios::sync_with_stdio(false);

    while (solve()) {}

    return 0;
}
accuracy: 1
time_ms: 1290
memory_kb: 3400
final_rank: 4

code_snippet: #include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "string"
#include "map"
#include "unordered_map"
#include "unordered_set"
#include "iomanip"
#include "cmath"
#include "random"
#include "bitset"
#include "cstdio"
#include "numeric"
#include "cassert"
#include "ctime"

using namespace std;

constexpr long long int MOD = 1000000007;
//constexpr int MOD = 1000000007;
//constexpr int MOD = 998244353;
//constexpr long long int MOD = 998244353;
constexpr double EPS = 1e-9;

//int N, M, K, T, H, W, L, R;
long long int N, M, K, T, H, W, L, R;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);


	while (cin >> N >> M, N) {
		cin >> H >> W;
		vector<string>s(H);
		for (auto &i : s)cin >> i;
		vector<int>damage(256);
		cin >> K;
		while (K--) {
			char c;
			cin >> c >> L;
			damage[c] = L;
		}
		cin >> L;
		vector<pair<char, int>>mv(L);
		for (auto &i : mv)cin >> i.first >> i.second;
		cin >> K;
		vector<int>p(K);
		for (auto &i : p)cin >> i;
		vector<int>dp(1 << K, N);
		for (int i = 0; i < 1 << K; i++) {
			for (int j = 0; j < K; j++) {
				if ((i >> j) & 1) {
					dp[i] += p[j];
					dp[i] = min(dp[i], (int)M);
				}
			}
		}
		int y = 0, x = 0;
		for (auto i : mv) {
			while (i.second--) {
				int dy = 0, dx = 0;
				if (i.first == 'D')dy = 1;
				if (i.first == 'U')dy = -1;
				if (i.first == 'R')dx = 1;
				if (i.first == 'L')dx = -1;
				y += dy, x += dx;
				int minus = damage[s[y][x]];
				for (auto &j : dp)j -= minus;
				for (int j = 0; j < 1 << K; j++) {
					if (dp[j] <= 0)dp[j] = -MOD;
					for (int k = 0; k < K; k++) {
						if ((j >> k) & 1)continue;
						dp[j | (1 << k)] = min((int)M, max(dp[j | (1 << k)], dp[j] + p[k]));
					}
				}
			}
		}
		if (dp.back() > 0) {
			cout << "YES\n";
		}
		else {
			cout << "NO\n";
		}
	}
}
accuracy: 1
time_ms: 2810
memory_kb: 3072
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;
int main(){
  while (1){
    int HPi, HPm;
    cin >> HPi >> HPm;
    if (HPi == 0 && HPm == 0){
      break;
    }
    int R, C;
    cin >> R >> C;
    vector<vector<char>> a(R, vector<char>(C));
    for (int i = 0; i < R; i++){
      for (int j = 0; j < C; j++){
        cin >> a[i][j];
      }
    }
    int T;
    cin >> T;
    map<char, int> mp;
    for (int i = 0; i < T; i++){
      char c;
      int d;
      cin >> c >> d;
      mp[c] = d;
    }
    int S;
    cin >> S;
    int cy = 0, cx = 0;
    vector<int> y, x;
    int N = 0;
    for (int i = 0; i < S; i++){
      char d;
      int n;
      cin >> d >> n;
      for (int j = 0; j < n; j++){
        if (d == 'U'){
          cy--;
        }
        if (d == 'D'){
          cy++;
        }
        if (d == 'L'){
          cx--;
        }
        if (d == 'R'){
          cx++;
        }
        y.push_back(cy);
        x.push_back(cx);
        N++;
      }
    }
    int P;
    cin >> P;
    vector<int> p(P);
    for (int i = 0; i < P; i++){
      cin >> p[i];
    }
    vector<vector<int>> b(R, vector<int>(C));
    for (int i = 0; i < R; i++){
      for (int j = 0; j < C; j++){
        b[i][j] = mp[a[i][j]];
      }
    }
    vector<vector<int>> dp(N + 1, vector<int>(1 << P, -1));
    dp[0][0] = HPi;
    for (int i = 0; i < N; i++){
      for (int j = 0; j < (1 << P); j++){
        for (int k = 0; k < P; k++){
          if (j >> k & 1){
            if (dp[i][j - (1 << k)] != -1){
              dp[i][j] = max(dp[i][j], min(dp[i][j - (1 << k)] + p[k], HPm));
            }
          }
        }
      }
      for (int j = 0; j < (1 << P); j++){
        if (dp[i][j] > b[y[i]][x[i]]){
          dp[i + 1][j] = dp[i][j] - b[y[i]][x[i]];
        }
      }
    }
    if (dp[N][(1 << P) - 1] == -1){
      cout << "NO" << endl;
    } else {
      cout << "YES" << endl;
    }
  }
}
accuracy: 1
time_ms: 3180
memory_kb: 18972
final_rank: 17

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define mp make_pair
#define si(x) int(x.size())
const int mod=1000000007,MAX=35,INF=1<<30;
int dp[1005][1<<12];
vector<int> dh={0,1,0,-1},dw={1,0,-1,0};
int damage[105][105],heal[15];
vector<int> mov;
int maxi,K;

void solve(){
    int h=0,w=0;
    for(int t=0;t<si(mov);t++){
        h+=dh[mov[t]];
        w+=dw[mov[t]];
        for(int bit=0;bit<(1<<K);bit++){
            if(dp[t][bit]==0) continue;
            
            for(int i=0;i<K;i++){
                if(bit&(1<<i)) continue;
                
                chmax(dp[t][bit|(1<<i)],min(maxi,dp[t][bit]+heal[i]));
            }
            
            chmax(dp[t+1][bit],dp[t][bit]-damage[h][w]);
        }
    }
}

int main(){
    
    std::ifstream in("text.txt");
    std::cin.rdbuf(in.rdbuf());
    cin.tie(0);
    ios::sync_with_stdio(false);
    
    string U="RDLU";
    while(1){
        memset(dp,0,sizeof(dp));
        int x;cin>>x>>maxi;
        dp[0][0]=x;
        if(x==0) break;
        
        int H,W;cin>>H>>W;
        mov.clear();
        vector<string> S(H);
        for(int i=0;i<H;i++) cin>>S[i];
        int T;cin>>T;
        map<char,int> MA;
        for(int i=0;i<T;i++){
            char c;int a;cin>>c>>a;
            MA[c]=a;
        }
        for(int i=0;i<H;i++){
            for(int j=0;j<W;j++){
                damage[i][j]=MA[S[i][j]];
            }
        }
        cin>>T;
        
        for(int i=0;i<T;i++){
            char c;int a;cin>>c>>a;
            while(a--){
                for(int j=0;j<4;j++){
                    if(U[j]==c) mov.push_back(j);
                }
            }
        }
        
        cin>>K;
        for(int i=0;i<K;i++){
            cin>>heal[i];
        }
        
        solve();
        
        bool ok=false;
        
        for(int j=0;j<(1<<K);j++) if(dp[si(mov)][j]) ok=true;
        
        if(ok) cout<<"YES\n";
        else cout<<"NO\n";
        
    }
}
accuracy: 1
time_ms: 1550
memory_kb: 19376
final_rank: 10

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vll = vector<ll>;
using vvll = vector<vll>;
using P = pair<int, int>;
const double eps = 1e-8;
const ll MOD = 1000000007;
const int INF = INT_MAX / 2;
const ll LINF = LLONG_MAX / 2;
template <typename T1, typename T2>
bool chmax(T1 &a, const T2 &b) {
  if(a < b) {a = b; return true;}
  return false;
}
template <typename T1, typename T2>
bool chmin(T1 &a, const T2 &b) {
  if(a > b) {a = b; return true;}
  return false;
}
template<typename T1, typename T2>
ostream& operator<<(ostream &os, const pair<T1, T2> p) {
  os << p.first << ":" << p.second;
  return os;
}
template<class T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  for(int i=0;i<((int)(v.size()));++i) {
    if(i) os << " ";
    os << v[i];
  }
  return os;
}
bool solve() {
  int h, hma; cin >> h >> hma;
  if(h == 0) return false;
  int r, c; cin >> r >> c;
  vector<string> g(r);
  for(int i=0;i<(r);++i) {
    cin >> g[i];
  }
  int t; cin >> t;
  vi mp(26);
  for(int i=0;i<(t);++i) {
    char c; cin >> c;
    int k; cin >> k;
    mp[c-'A'] = k;
  }
  int s; cin >> s;
  vector<int> dr(s), dc(s), num(s);
  for(int i=0;i<(s);++i) {
    char c; cin >> c >> num[i];
    if(c == 'L') {
      dc[i] = -1;
    } else if(c == 'R') {
      dc[i] = 1;
    } else if(c == 'U') {
      dr[i] = -1;
    } else if(c == 'D') {
      dr[i] = 1;
    }
  }
  int p; cin >> p;
  vi tmpv(p);
  for(int i=0;i<(p);++i) {
    cin >> tmpv[i];
  }
  set<P> val;
  for(int i=(1);i<(1<<p);++i) {
    int now = 0;
    for(int j=0;j<(p);++j) {
      if((i>>j)&1) now += tmpv[j];
    }
    val.insert({now, i});
  }
  P pos = {0, 0};
  bool ok = true;
  for(int i=0;i<(s);++i) {
    if(!ok) break;
    for(int j=0;j<(num[i]);++j) {
      int nr = pos.first + dr[i], nc = pos.second + dc[i];
      int nowval = mp[g[nr][nc]-'A'];
      h -= nowval;
      if(h <= 0) {
        auto it = val.lower_bound(make_pair(-h+1, 0));
        if(it == val.end()) {
          ok = false;
          break;
        }
        if(min(h + nowval + it->first, hma) - nowval <= 0) {
          ok = false;
          break;
        }
        h = min(h + nowval + it->first, hma) - nowval;
        int bit = it->second;
        vector<P> er;
        for(auto &e: val) {
          if(e.second & bit) {
            er.emplace_back(e);
          }
        }
        for(auto &e: er) {
          val.erase(e);
        }
      }
      pos = {nr, nc};
    }
  }
  cout << (ok ? "YES" : "NO") << endl;
  return true;
}
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << fixed << setprecision(10);
  while(solve()) {}
}
accuracy: 1
time_ms: 20
memory_kb: 3500
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;

template<class T>
bool chmax(T& a, const T& b) {
    if (a < b) { a = b; return true; }
    return false;
}
template<class T>
bool chmin(T& a, const T& b) {
    if (b < a) { a = b; return true; }
    return false;
}

// std::vector Declaration
template<typename T>
vector<T> make_v(size_t a) { return vector<T>(a); }
template<typename T, typename... Ts>
auto make_v(size_t a, Ts... ts) {
    return vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...));
}

// std::vector Declaration and Initialization
template<typename T>
vector<T> make_vector(size_t a, T x) { return vector<T>(a, x); }
template<typename T, typename U, typename... Ts>
auto make_vector(size_t a, U b, Ts... ts) {
    return vector<decltype(make_vector<T>(b,ts...))>(a, make_vector<T>(b, ts...));
}

// std::vector Input
template<typename T>
istream& operator>>(istream& is, vector<T>& v) {
    for (auto &e : v) is >> e;
    return is;
}

// std::vector Debug
template<typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
    os << "[";
    bool a = 1;
    for (auto e : v) {
        os << (a ? "" : " ");
        os << e;
        a = 0;
    }
    os << "]";
    return os;
}

// std::array Debug
template<typename T, size_t n>
ostream& operator<<(ostream& os, const array<T, n>& v) {
    os << "[";
    bool a = 1;
    for (auto e : v) {
        os << (a ? "" : " ");
        os << e;
        a = 0;
    }
    os << "]";
    return os;
}

// std::deque Debug
template<typename T>
ostream& operator<<(ostream& os, const deque<T>& d) {
    os << "[";
    bool a = 1;
    for (auto e : d) {
        os << (a ? "" : " ");
        os << e;
        a = 0;
    }
    os << "]";
    return os;
}

// std::pair Debug
template<typename T, typename U>
ostream& operator<<(ostream& os, const pair<T, U>& p) {
    os << "(" << p.first << " " << p.second << ")";
    return os;
}

// std::set Debug
template<typename T>
ostream& operator<<(ostream& os, const set<T>& st) {
    os << "{";
    bool a = 1;
    for (auto e : st) {
        os << (a ? "" : " ");
        os << e;
        a = 0;
    }
    os << "}";
    return os;
}

// std::multiset Debug
template<typename T>
ostream& operator<<(ostream& os, const multiset<T>& st) {
    os << "{";
    bool a = 1;
    for (auto e : st) {
        os << (a ? "" : " ");
        os << e;
        a = 0;
    }
    os << "}";
    return os;
}

// std::map Debug
template<typename T, typename U>
ostream& operator<<(ostream& os, const map<T, U>& mp) {
    os << "{";
    bool a = 1;
    for (auto e : mp) {
        os << (a ? "" : " ");
        os << e.first << ":" << e.second;
        a = 0;
    }
    os << "}";
    return os;
}

// std::tuple Debug
template<int N, class Tuple>
void out(ostream& os, const Tuple& t){}
template<int N, class Tuple, class H, class ...Ts>
void out(ostream& os, const Tuple& t) {
    if (N) os << " ";
    os << get<N>(t);
    out<N+1,Tuple,Ts...>(os, t);
}
template<class ...Ts>
ostream& operator<<(ostream& os, const tuple<Ts...>& t) {
    os << "(";
    out<0,tuple<Ts...>,Ts...>(os, t);
    os << ")";
    return os;
}

// Debug
#define DUMP(x) cerr<<#x<<" = "<<(x)<<endl

// Weighted edge
template<typename T>
struct edge {
    int src, to;
    T cost;

    edge() {}
    edge(int to, T cost) : src(-1), to(to), cost(cost) {}
    edge(int src, int to, T cost) : src(src), to(to), cost(cost) {}

    friend ostream& operator<<(ostream& os, const edge& e) {
        return os << "(" << e.src << "->" << e.to << ":" << e.cost << ")";
    }
};

using LL = int64_t;

#define fs first
#define sc second

const int64_t MOD = 1e9+7;


int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(10);

    while (true) {
        int HPinit, HPmax; cin >> HPinit >> HPmax;
        if (HPinit == 0) break;

        int R, C; cin >> R >> C;
        vector<string> a(R); cin >> a;
        int T; cin >> T;
        map<char,int> d;
        for (int i = 0; i < T; ++i) {
            char c; cin >> c;
            cin >> d[c];
        }
        int S; cin >> S;
        string s;
        for (int i = 0; i < S; ++i) {
            char c; cin >> c;
            int n; cin >> n;
            for (int j = 0; j < n; ++j) {
                s += c;
            }
        }
        int P; cin >> P;
        vector<int> p(P); cin >> p;

        map<char,int> dx, dy;
        dx['R'] = 1, dx['L'] = -1;
        dy['D'] = 1, dy['U'] = -1;

        vector<int> x(s.size()+1), y(s.size()+1);
        for (int i = 0; i < s.size(); ++i) {
            x[i+1] = x[i] + dx[s[i]];
            y[i+1] = y[i] + dy[s[i]];
        }

        auto dp = make_v<int>(s.size()+1, 1<<P);
        dp[0][(1<<P)-1] = HPinit;
        for (int i = 0; i < s.size(); ++i) {
            char trap = a[y[i+1]][x[i+1]];
            for (int bit = 0; bit < 1<<P; ++bit) {
                if (dp[i][bit] == 0) continue;
                chmax(dp[i+1][bit], dp[i][bit] - d[trap]);
                for (int j = 0; j < P; ++j) if (bit >> j & 1) {
                    chmax(dp[i+1][bit & ~(1<<j)],
                            min(dp[i][bit] + p[j], HPmax) - d[trap]);
                }
            }
        }

        cout << (dp[s.size()][0] ? "YES" : "NO") << endl;
    }

    return 0;
}
accuracy: 1
time_ms: 3430
memory_kb: 18980
final_rank: 19