[Backtracking] C034_openj_ count 24 (essentially unchanged)

1. Problem

Given 4 positive integers less than 10, you can use the addition, subtraction, multiplication and division of 4 operations and parentheses to connect these 4 numbers to get an expression. The question now is whether there is a way to make the result of the expression equal to 24.

The addition, subtraction, multiplication and division, and the operation results and priority of the parentheses are consistent with our usual definition (the definition of division here is real division).

For example, for 5, 5, 5, 1, we know that 5 * (5 – 1/5) = 24, so we can get 24. As another example, for 1, 1, 4, 2, we can never get 24.

Input

The input data includes multiple lines, each line gives a set of test data, including 4 less than 10 positive integers. The last set of test data includes 4 zeros, indicating the end of the input, this set of data does not need to be processed.

Output

For each set of test data, output a line, if you can get 24, output "YES"; otherwise, output "NO".

样例输入
5 5 5 1
1 1 4 2
0 0 0 0
样例输出
YES
NO

Second, Solution

Method 1: Backtracking

  • Use an operator to exhaust the number, then go back to the previous operation, select the next operation, and repeat the process.
  • When a deep search is completed, the state needs to be restored.
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
	static boolean done;
	static double[] a;
	static double INF = -1e6 * 1.0;
	final static int N = 4;
	static double ops(double a, double b, double k) {
		if (k == 0)      return a + b;
		else if (k == 1) return a - b;
		else if (k == 2) return a * b;
		else             return a / b;
	}
	static void dfs(int x) {
		if (done)
			return;
		Arrays.sort(a);
		if (x == N-1) {
		    if (Math.abs(a[N-1] - 24) < 0.00001)
			    done = true;
			return;
		}
		double[] t = Arrays.copyOf(a, a.length);
		for (int i = x; i < N; i++)
		for (int j = x; j < N; j++) {
		    if (i == j)
		        continue;
			for (int k = 0; k < N; k++) {
				a[i] = ops(a[i], a[j], k);
				a[j] = INF;
				dfs(x+1);
				a = Arrays.copyOf(t, t.length);;
			}
		}
	}
    public static void main(String[] args) throws IOException {  
        Scanner sc = new Scanner(new BufferedInputStream(System.in));
        BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
        
		while (true) {
		    a = new double[N];
			for (int i = 0; i < a.length; i++) {
				a[i] = sc.nextDouble();
			}
			if (a[0] == 0 && a[1] == 0 && a[2] == 0 && a[3] == 0)
				return;
			done = false;
			dfs(0);
			if (done)System.out.println("YES");
			else 	 System.out.println("NO");
		}
    }
}

Complexity analysis

  • time complexity: O ( 2 4 ) O (2 ^ 4)
  • Space complexity: O ( n ) O (n)
Published 714 original articles · praised 199 · 50,000+ views

Guess you like

Origin blog.csdn.net/qq_43539599/article/details/105624332