标签:use turn put through rac 开始 each action add
Given four numbers, can you get twenty-four through the addition, subtraction, multiplication, and division? Each number can be used only once.
Input
The input consists of multiple test cases. Each test case contains 4 integers A, B, C, D in a single line (1 <= A, B, C, D <= 13).
Output
For each case, print the “Yes” or “No”. If twenty-four point can be get, print “Yes”, otherwise, print “No”.
Sample Input
2 2 3 9 1 1 1 1 5 5 5 1
Sample Output
Yes No Yes
Hint
For the first sample, (2/3+2)*9=24.
emmmmm,是一道需要姿势的题,四个数需要随机排序,开始想的很麻烦。后来看了标程发现姿势很重要。在四个数中随意选两个做四则运算保存结果作为一个新的数,将新生成的三个数重复这个操作,直到最后变成一个数,检查一个数是不是24即可。
#include<iostream> #include<math.h> using namespace std; double num[4]; bool flag; bool equel(double a, double b) { if(fabs(a - b) <= 1e-10) return true; return false; } void DFS(int n) { if(flag||(n==1&&fabs(num[0]-24)<=1e-10)) { flag=true; return; } else { for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) { double c1 = num[i], c2 = num[j]; num[j] = num[n - 1]; num[i] = c1 + c2; DFS(n - 1); num[i] = c1 - c2; DFS(n - 1); num[i] = c2 - c1; DFS(n - 1); num[i] = c1 * c2; DFS(n - 1); if(!equel(c2, 0)) { num[i] = c1 / c2; DFS(n - 1); } if(!equel(c1, 0)) { num[i] = c2 / c1; DFS(n - 1); } num[i] = c1; num[j] = c2; } } } int main() { while(cin>>num[0]>>num[1]>>num[2]>>num[3]) { flag=false; DFS(4); if(flag==1) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }
CSU - 1600 : Twenty-four point
标签:use turn put through rac 开始 each action add
原文地址:http://www.cnblogs.com/xibeiw/p/7252406.html