Broken Calculator

2019-04-17 08:12发布

问题:

Problem Statement:

There is a broken calculator. Only a few of the digits [0 to 9] and operators [+, -, *, /] are working.

A req no. needs to be formed using the working digits and the operators. Each press on the keyboard is called an operation.

  • = operator is always working and is used when the req no. is formed using operators.
  • -1 needs to be printed in case the req no. cannot be formed using the digits and the operators provided OR exceeds the max no. of operations allowed.
  • At no point in time during the calculation of the result, the no. should become negative or exceed 999 [0 <= calcno <= 999]

Input:

  • 1st line contains 3 space separated nos: no. of working digits, no. of working operators, max. no of operations allowed.
  • 2nd line contains space separated working digits.
  • 3rd line contains space separated working operators [1 represents +, 2 represents -, 3 represents *, 4 represents /].
  • 4th line contains the req. no to be formed.

Output:

Find the minimum required operations to form the req no.


Example:

Input 1:

2 1 8  
2 5  
3  
50 

Possible ways:

Case 1: 2*5*5 = -> 6 operations
Case 2: 2*25 = -> 4 operations

4 is the req Answer


Input 2:

3 4 8  
5 4 2  
3 2 4 1  
42  

Possible ways:
Case 1: 42 -> 2 operations (direct key in)
Case 2: 5*4*2+2 = -> 8 operations
..........some other ways

2 is the req Answer


I am not getting a proper approach to this problem.
Can someone suggest some ways to approach the problem.

回答1:

Giving some more context what vish4071 said in the comments.

Set up a graph in the following way: Starting the graph with a root, and than the new node are the number you're aloud to use (for the example this is 2 and 5). And build up the graph level by level. Make each level in the following way, a new node will consist either of adding number or a operator which you're aloud to use. After each operator there cannot be another operator.

If the node has a higher value than the Target value, than kill the node (target as end note), this only works for this example (if the operators are * and +). If you would be able to use the - and / operator this is not vallid.

Do this till you find the required value, and the level (+1, due to the = operation) is you're answer.

And example of the graph is given below

for your first example:
D=0    D=1    
       5
      /
Root /
     \
      \2


D=1    D=2   d=3   d=4
            --2
           / 
          /
        (*)___5  --> reaches answer but at level 6
        /   
       /     (*)___2  --> complete
      /     /   \  5
     /     /
  2 /____25_252    --> end node
    \     \
     \     \ 
      \     
       \    225    --> end node
        \  /
         22__222   --> end node
           \            
            (*)

This is slightly better than brute forcing, maybe there is a more optimal way.