Description
寒假刚刚过去,小明的数学作业还没完成,其中一道题目的意思是给定n个整数,
每两个整数间(包括第一个整数前)都存在一个空位,求是否可以在上面填写四则运算符使得n个数的运算值等于m, 如:1 + 2 * 3 = 7 (除法结果向下取整),你可以帮助他完成作业吗?
Input
输入数据首先是一个t(t <= 15),后面跟t组数据,每组数据由两行构成,第一行由两个整数n(n <= 12)和m(m < 2^31)构成,第二行由n个整数a[i] (0 <= i < n && a[i] < 2^31)构成。
Output
如果存在运算值等于m,则输出”YES”,否则输出”NO”;
Sample Input
2
3 7
1 2 3
3 8
1 2 3
Sample Output
YES
NO
比赛时一直WA50%,当时想复杂了,用逆波兰式。。。但又不熟,一直到比赛结束也没能AC
赛后虽然改好了,然而却超时了,泪奔~~~,好吧,是我太水了
借阅了大神的代码,惊叹其简洁优雅,学习了。直接用栈是大材小用,用了也会超时,考虑到题目特点,用cur记录累计的和,用head模拟栈头
好了,照例上代码~
#include <iostream>
using namespace std;
typedef long long LL;
int t, n;
LL m, arr[1000];
bool Dfs(LL cur, LL head, int index) {
if (index == n) {
return cur + head == m;
}
return Dfs(cur + head, arr[index], index + 1) ||
Dfs(cur + head, -arr[index], index + 1) ||
Dfs(cur, head*arr[index], index + 1) ||
(arr[index] != 0 && Dfs(cur, head/arr[index], index + 1));
}
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d%lld", &n, &m);
for (int i = 0; i < n; ++i) {
scanf("%lld", &arr[i]);
}
bool yes = Dfs(0, arr[0], 1) || Dfs(0, -arr[0], 1);
printf("%s\n", yes ? "YES" : "NO");
}
return 0;
}