題目連接:http://pat.zju.edu.cn/contests/ds/2-08html
一副撲克牌的每張牌表示一個數(J、Q、K分別表示十一、十二、13,兩個司令都表示6)。任取4張牌。即獲得4個1~13的數,請加入運算符(規定爲加+ 減- 乘* 除/ 四種)使之成爲一個運算式。post
每個數僅僅能參與一次運算。4個數順序可以隨意組合,4個運算符隨意取3個且可以反覆取。運算聽從必定優先級別,可加括號控制。終於使運算結果爲24。請輸出一種解決方式的表達式,用括號表示運算優先。假設沒有一種解決方式,則輸出-1表示無解。spa
輸入格式說明:code
輸入在一行中給出4個整數,每個整數取值在[1, 13]。htm
輸出格式說明:blog
輸出一種解決方式的表達式,用括號表示運算優先。假設沒有解決方式。請輸出-1。ip
例子輸入與輸出:ci
序號 | 輸入 | 輸出 |
1 | 2 3 12 12 |
((3-2)*12)+12 |
2 | 5 5 5 5 |
(5*5)-(5/5) |
3 | 1 3 5 6 |
(1+(3*6))+5 |
4 | 8 13 9 4 |
8+((13-9)*4) |
5 | 2 13 7 7 |
2*(13-(7/7)) |
6 | 5 5 5 2 |
-1 |
PS:get
此題思路:http://blog.sina.com.cn/s/blog_81727a7f01017e9a.htmlit
暴力枚舉每次所選的數字和運算符的五種不一樣運算姿式!
代碼例如如下:
#include <cstdio> char op[5]= {'#','+','-','*','/',}; double cal(double x,double y,int op) { switch(op) { case 1: return x+y; case 2: return x-y; case 3: return x*y; case 4: return x/y; } } double cal_m1(double i,double j,double k,double t,int op1,int op2,int op3) { double r1,r2,r3; r1 = cal(i,j,op1); r2 = cal(r1,k,op2); r3 = cal(r2,t,op3); return r3; } double cal_m2(double i,double j,double k,double t,int op1,int op2,int op3) { double r1,r2,r3 ; r1 = cal(i,j,op1); r2 = cal(k,t,op3); r3 = cal(r1,r2,op2); return r3; } double cal_m3(double i,double j,double k,double t,int op1,int op2,int op3) { double r1,r2,r3; r1 = cal(j,k,op2); r2 = cal(i,r1,op1); r3 = cal(r2,t,op3); return r3; } double cal_m4(double i,double j,double k,double t,int op1,int op2,int op3) { double r1,r2,r3 ; r1 = cal(k,t,op3); r2 = cal(j,r1,op2); r3 = cal(i,r2,op1); return r3; } double cal_m5(double i,double j,double k,double t,int op1,int op2,int op3) { double r1,r2,r3; r1 = cal(j,k,op2); r2 = cal(r1,t,op3); r3 = cal(i,r2,op1); return r3; } int get_24(int i,int j,int k,int t) { for(int op1 = 1; op1 <= 4; op1++) { for(int op2 = 1; op2 <= 4; op2++) { for(int op3 = 1; op3 <= 4; op3++) { if(cal_m1(i,j,k,t,op1,op2,op3) == 24) { printf("((%d%c%d)%c%d)%c%d\n",i,op[op1],j,op[op2],k,op[op3],t); return 1; } if(cal_m2(i,j,k,t,op1,op2,op3) == 24) { printf("(%d%c%d)%c(%d%c%d)\n",i,op[op1],j,op[op2],k,op[op3],t); return 1; } if(cal_m3(i,j,k,t,op1,op2,op3) == 24) { printf("(%d%c(%d%c%d))%c%d\n",i,op[op1],j,op[op2],k,op[op3],t); return 1; } if(cal_m4(i,j,k,t,op1,op2,op3) == 24) { printf("%d%c(%d%c(%d%c%d))\n",i,op[op1],j,op[op2],k,op[op3],t); return 1; } if(cal_m5(i,j,k,t,op1,op2,op3) == 24) { printf("%d%c((%d%c%d)%c%d)\n",i,op[op1],j,op[op2],k,op[op3],t); return 1; } } } } return 0; } int main() { int a[4]; int t1, t2, t3, t4; int flag; for(int i = 0; i < 4; i++) scanf("%d",&a[i]); for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) { if(j==i) continue; for(int k = 0; k < 4; k++) { if(i==k||j==k) continue; for(int t = 0; t < 4; t++) { if(t==i||t==j||t==k) continue; t1 = a[i], t2= a[j], t3= a[k], t4= a[t]; flag = get_24(t1,t2,t3,t4); if(flag ==1) break; } if(flag == 1) break; } if(flag == 1) break; } if(flag == 1) break; } if(flag == 0) printf("-1\n"); return 0; }