題意:給定N個長度爲4的字符串,字符串中只有數字,現在可以將某個字符串全排列,通過在數字之間進行加減乘除和括號5種操作,得到的值是否等於10。求出這N個字符串是否都滿足條件。
對於每個字符串,求出它的全排列,對於它的每一個排列,枚舉兩兩之間的加減乘除操作,括號的優先級就用dfs枚舉,這樣能求出所有的情況。
發現錯在一個很神奇的地方,當除法操作,除數爲0時,返回-INF(INF爲INT_MAX),和返回隨意一個值,得到的答案不同,返回-INF時就wa了..................
#include <iostream>
#include <algorithm>
#include <cmath>
#include<functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <queue>
#include <stack>
#include <climits>//形如INT_MAX一類的
#define MAX 1111
#define INF 0x7FFFFFFF
using namespace std;
int n;
char s[11];
int a[11],b[11],op[11],pos[11];
int tag;
int cal(int x,int y,int kind) {
if(kind == 0) return x + y;
if(kind == 1) return x - y;
if(kind == 2) return x * y;
if(kind == 3) {
if(y == 0) return 0;
return x / y;
}
}
void dfs(int ope[],int num[],int step) {
if(tag == 1) return ;
if(step == 0) {
//cout << num[0] << endl;
if(num[0] == 10) tag = 1;
return ;
}
// if(step == 1) {
// cout << num[0] << ' ' << num[1] << endl;
// }
int tmp1[11],tmp2[11];
for(int i=0; i<step; i++) {
for(int j=0; j<i; j++) tmp1[j] = num[j];
tmp1[i] = cal(num[i],num[i+1],ope[i]);
for(int j=i+1; j<step; j++) tmp1[j] = num[j+1];
for(int j=0; j<i; j++) tmp2[j] = ope[j];
for(int j=i; j<step-1; j++) tmp2[j] = ope[j+1];
dfs(tmp2,tmp1,step - 1);
}
}
bool solve() {
tag = 0;
for(int i=0; i<4; i++) b[i] = a[i];
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
for(int k=0; k<4; k++) {
op[0] = i;
op[1] = j;
op[2] = k;
dfs(op,b,3);
if(tag) return 1;
}
}
}
return 0;
}
int main() {
while(scanf("%d",&n) && n) {
int flag = 1;
for(int i=0; i<n; i++) {
scanf("%s",s);
int ok = 0;
if(flag == 0) continue;
for(int j=0; j<4; j++) a[j] = s[j] - '0';
sort(a,a+4);
do {
if(solve()) {
ok = 1;
break;
}
} while(next_permutation(a,a+4));
if(!ok) {
flag = 0;
}
}
if(flag) puts("TRUE");
else puts("BUSTED");
}
return 0;
}