#P6371. Divisible Number Construction

    ID: 19587 Type: Default 1000ms 256MiB

Divisible Number Construction

Divisible Number Construction

You are given three integers \(A\), \(B\) and \(X\), and a string consisting of digits. Your task is to form numbers by permuting all of the digits (each digit must be used exactly once) so that each resulting number satisfies the following conditions:

  • The number is in the interval \([A,B]\).
  • The number is divisible by \(X\).

Leading zeros are allowed in the permutation, and the numeric value is computed in the usual way. Output all distinct numbers satisfying the conditions in ascending order. If no valid number exists, print -1.

Note: Two numbers are considered the same if their integer values are equal (i.e. duplicates arising from repeated digits should be printed only once).

inputFormat

The input consists of two lines:

  1. The first line contains three space-separated integers: \(A\), \(B\) and \(X\) (with \(A \leq B\) and \(X > 0\)).
  2. The second line contains a non-empty string of digits.

outputFormat

Output all distinct numbers (formed by using all the digits exactly once) in ascending order that lie in the interval \([A,B]\) and are divisible by \(X\), separated by a single space. If no such number exists, print -1.

sample

10 1000 2
123
132 312