Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- n = STDIN.readline().strip().to_i()
- numbers = STDIN.readline().split(/\s/).compact().map(&:to_i)
- answer = STDIN.readline().strip().to_i()
- if (numbers.length != n) then
- printf("array size mismatch\n")
- exit
- end
- def exit_no_solution()
- printf("no solution\n")
- exit
- end
- min = numbers[0]
- i = 1; while (i < n) do
- min -= numbers[i]
- i += 1 ## it's better to use "i++", but Ruby doesn't have increment
- end
- if (answer < min) then
- exit_no_solution()
- end
- max = 0
- i = 0; while i < n do
- max += numbers[i]
- i += 1 ## it's better to use "i++", but Ruby doesn't have increment
- end
- if (answer > max) then
- exit_no_solution()
- end
- ## array with signs: "false" means "-", "true" means "+" %)
- signs = Array.new(n, false) ### [false, false, false, ...]
- signs[0] = true ### [true, false, false, ...]
- while true do
- result = 0
- i = 0; while i < n do
- if signs[i] then
- result += numbers[i]
- else
- result -= numbers[i]
- end
- i += 1 ## it's better to use "i++", but Ruby doesn't have increment
- end
- if result == answer then
- printf("%d = ", answer)
- i = 0; while i < n do
- if (i != 0) then
- if signs[i] then
- printf(" + ")
- else
- printf(" - ")
- end
- end
- printf("%d", numbers[i])
- i += 1 ## it's better to use "i++", but Ruby doesn't have increment
- end
- printf("\n")
- exit
- end
- ## treat signs as little-endian binary value and implement increment logic on top of it
- ## k - index of last "false" element
- k = n; while k != 0 do
- k -= 1 ## it's better to use "k--", but Ruby doesn't have decrement
- if ! signs[k] then
- break
- end
- end
- ## if k points to first element then our "little-endian value" has reached maximum value
- ## nothing to do here, sorry
- if k == 0 then
- break
- end
- ## increment element
- signs[k] = true
- ## decrement elements after current
- i = k + 1; while i < n do
- signs[i] = false
- i += 1 ## it's better to use "i++", but Ruby doesn't have increment
- end
- ## proceed to next iteration
- end
- exit_no_solution()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement