problems / 131

Recovering Dotted Addresses

easy backtracking strings 1000 ms · 256 MB

Recovering Dotted Addresses

A buggy log shipper on one of your edge proxies stripped every . out of the client-address column, so a line that should have read 10.1.0.23 now just says 101023. Before you can match these lines against the firewall rules, you need to know which addresses each mangled entry could originally have been.

An IPv4 address in dotted form is four octets joined by dots. Each octet is a decimal number from 0 to 255, written without leading zeros: 0, 7 and 255 are valid octets, while 00, 01, 256 and the empty string are not.

For each digit string from the log, find every valid IPv4 address that turns back into exactly that string when its three dots are removed. In other words, insert exactly three dots into the string, without reordering, adding or dropping any digit, so that all four pieces are valid octets.

Input

The first line contains t (1 ≤ t ≤ 2·10^4), the number of log entries.

Each of the next t lines contains one entry: a string s of decimal digits 0–9 with 1 ≤ |s| ≤ 20.

Output

For each entry, in input order, first print a line with k, the number of valid addresses it could have been (possibly 0). Then print those k addresses, one per line, in lexicographic order as strings (characters compared by ASCII code, so . sorts before every digit).

Notes

In the first example, 25525511135 can only be split as 255.255.11.135 or 255.255.111.35; any other placement of the dots produces an octet above 255. The string 0000 gives only 0.0.0.0, because a piece such as 00 has a leading zero. The last entry has 13 digits, more than four octets can hold, so its count is 0.

In the second example, note that 2.5.50.255 comes before 2.55.0.255: the strings first differ at the fourth character, where . is smaller than 5.

Example 1

Input

4
25525511135
0000
101023
1111111111111

Output

2
255.255.11.135
255.255.111.35
1
0.0.0.0
5
1.0.10.23
1.0.102.3
10.1.0.23
10.10.2.3
101.0.2.3
0

Example 2

Input

3
2550255
123
256256256256

Output

7
2.5.50.255
2.55.0.255
25.5.0.255
25.50.2.55
25.50.25.5
255.0.2.55
255.0.25.5
0
0

Hints · reveal one at a time if you're stuck

Hint 1

An address has exactly four octets, and each octet has at most three digits. How does that limit the number of ways to cut the digit string, and what lengths can the whole string have?

Hint 2

A recursive search that tries every octet length at each step is small enough here. Think about the order the search produces addresses in, and check it against the required order, where a dot sorts before every digit.

report an issue Prefer your own editor? sooks prep 131 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.