Table of Contents

ExplanationImplementation

Explanation

We can complete search through all possible ways to create an arithmetic expression with a card hand. For each permutation of the card hand, we try every way of placing arithmetic operators. Note that there are two possible ways that parentheses can be arranged: ((( ) ) ), or (( ) ( )), so we must try both cases. The arithmetic expression with the maximum value that is not greater than 24 is our answer.

Time Complexity: O((# of cards)!×(# of operations)(# of cards)\mathcal{O}((\texttt{\# of cards})! \times (\texttt{\# of operations})^{(\texttt{\# of cards})}

Implementation

C++

#include <bits/stdc++.h>
using namespace std;
int ans;
int hand[4]; // The given card hand.
vector<int> hand_permutation; // The generated permutation of the card hand.
bool chosen[4]; // Whether a given card is present in `hand_permutation`.
// Function that takes in two numbers and an operation and returns the result.
int operation(int op, int num1, int num2) {

Java

import java.io.*;
import java.util.*;
public class Solution {
static int ans;
// The given card hand.
static int[] hand = new int[4];
// The generated permutation of the card hand.
static List<Integer> handPermutation = new ArrayList<>();
// Whether a given card is present in `hand_permutation`.

Python

ans = 0
hand = [0] * 4 # The given card hand.
hand_permutation = [] # The generated permutation of the card hand.
chosen = [False] * 4 # Whether a given card is present in `hand_permutation`.
# Function that takes in two numbers and an operation and returns the result.
def operation(op, num1, num2):
if op == 0:
return num1 + num2
elif op == 1:

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!