简体   繁体   中英

Algorithm which tells if a number is obtainable from a given set using only '+' ,'*' and brackets

I have two list of numbers, for every member of the second one I must tell if it's obtainable using all the numbers of the first one and placing '+' or '*' and as many '(' ')' I want.
I can't change the order .

List1 can contain a max of 20 elements beetween 1 and 100.
List2 can contain max 5 elements beetween 1 and 20'000.

EX:

List1=[2 4 3 5]  
List2=[19 15 24]

19-> 2+(4*3)+5  YES   
15              NO
24->2*(4+3+5)   YES

With brute force it takes ages to handle inputs with List1 larger than 10.

edit: numbers are always positive.

edit: I find the max and min numbers that are obtainable from the list and then I discard all the possibilities that have the target outside this range, then I try all the remaining ones.

 MAX=n1*n2*n3*....*ni    if there are 1 thei r added to their smallest neighbour

 MIN=n1+n2+....+ni       1 excluded

Still it's not fast enough when input are big (List1 longer than 10 or numbers in List2 bigger than 10000)

For each sublist of List1, compute the numbers between 1 and 20,000 that can be made with that sublist. The resulting DP bears resemblance to CYK .

I'm being somewhat vague here because this is almost certainly a programming contest problem.

@u mad is correct, but I'll give a little more detail.

Suppose that n = size of list 1 . For each 0 <= i < j < n you need to compute all of the distinct values in the range (1..20_000) that can be made from the numbers in the interval [i, j-1] . You can do this with recursion and memoization.

Once you've done this then the problem is easy.

你可以尝试一种智能蛮力,它可以通过块来丢弃方程组。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM