24 o'clock

Topic content:
Description of the problem: Enter 4 numbers, and see if you can get the result 24 through addition, subtraction, multiplication, and division. Each number is used only once.
enter description
Enter four positive integers

output description
If you can get 24 in some way, output 1, if not, output 0

input sample
6 6 6 6

Sample output
1
Idea: Because there are only four numbers, a full arrangement is set outside, the four numbers are arranged, and three loops are set inside to enumerate all the combination situations, because all situations are exhausted, so there is no need to consider priority issue. There are only four numbers, so the time complexity of this loop is not high. Of course, if there are more numbers, it will be too slow
code
#include <iostream>
#include <algorithm>
using namespace std;
int w[4] = {0,1,2,3};

intmain()
{
    int a[4];
    int i,j,k;
    cin >> a[0] >> a[1] >> a[2] >> a[3];
    sort (a,a+4);   
   do{
        for(i = 0; i < 4; i++)
        {
            for(j =0; j < 4;j++)
            {
                for(k = 0; k < 4; k++)
                {
                        int sum = 0;
                        switch(w[i])
                        {
                        case 0:sum = a[0] + a[1];break;
                        case 1:sum = a[0] - a[1];break;
                        case 2:sum = a[0] * a[1];break;
                        case 3:sum = a[0] / a[1];break;
                        default:break;
                        }
                        switch(w[j])
                        {
                        case 0:sum = sum + a[2];break;
                        case 1:sum = sum - a[2];break;
                        case 2:sum = sum * a[2];break;
                        case 3:sum = sum / a[2];break;
                        default:break;
                        }
                        switch(w[k])
                        {
                        case 0:sum = sum + a[3];break;
                        case 1:sum = sum - a[3];break;
                        case 2:sum = sum * a[3];break;
                        case 3:sum = sum / a[3];break;
                        default:break;
                        }    
                        if(sum == 24)
                        {
                            cout << "1" <<endl;
                            return 0;                
                        }
                }
            }
        }
    }while(next_permutation(a,a+4));
    cout << "0" <<endl;
    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325786334&siteId=291194637