#include <cstdio>
#include <cstring>
const int N = 1111;
char buf[N], op[N];
int lch[N], rch[N];
int h[N];
int build(char s[], int x, int y, int lch[], int rch[], char op[], int &nc) {
int i, u, c1, c2;
int p = 0;
c1 = c2 = -1;
if (x == y)
return -1;
if (y - x == 1) {
u = ++nc;
lch[u] = rch[u] = 0;
op[u] = s[x];
return u;
}
for (i = x; i < y; ++i) {
if (s[i] == '(')
++p;
if (s[i] == ')')
--p;
if (s[i] == '+' && !p)
c1 = i;
if (s[i] == '-' && !p)
c1 = i;
if (s[i] == '*' && !p)
c2 = i;
//putchar(s[i]);
}
if (c1 < 0)
c1 = c2;
if (c1 < 0)
return build(s, x + 1, y - 1, lch, rch, op, nc);
u = ++nc;
lch[u] = build(s, x, c1, lch, rch, op, nc);
rch[u] = build(s, c1 + 1, y, lch, rch, op, nc);
op[u] = s[c1];
return u;
}
int dfs(int u, int lch[], int rch[], char op[]) {
if (!lch[u]) {
char ch = op[u];
if (ch >= 'a' && ch <= 'z')
return h[ch - 'a'];
return 0;
}
if (op[u] == '+')
return dfs(lch[u], lch, rch, op) + dfs(rch[u], lch, rch, op);
if (op[u] == '-')
return dfs(lch[u], lch, rch, op) - dfs(rch[u], lch, rch, op);
return dfs(lch[u], lch, rch, op) * dfs(rch[u], lch, rch, op);
}
int v[N], n, size, m;
int ch[15];
bool used[15];
bool solve(int dep) {
if (dep == size) {
return dfs(1, lch, rch, op)==m;
}
for (int i = 0; i < n; ++i) {
if(used[i]) continue;
h[ch[dep]] = v[i];
used[i]=true;
if (solve(dep + 1))
return true;
used[i]=false;
}
return false;
}
int main() {
int i, len, nc;
while (~scanf("%d%d", &n, &v[0]) && (n | v[0])) {
for (i = 1; i < n; ++i)
scanf("%d", v + i);
nc = 0;
scanf("%d", &m);
scanf("%s", buf);
len = strlen(buf);
for (i = 0, size = 0; i < len; ++i)
if (buf[i] >= 'a' && buf[i] <= 'z')
ch[size++] = buf[i] - 'a';
build(buf, 0, len, lch, rch, op, nc);
bool flag = solve(0);
if (flag)
puts("YES");
else
puts("NO");
}
return 0;
}
HDU 3486
最新推荐文章于 2019-11-29 21:58:29 发布