#P2815. IPv6 Address Compression

    ID: 16076 Type: Default 1000ms 256MiB

IPv6 Address Compression

IPv6 Address Compression

Given a fully expanded IPv6 address in the form of eight groups of 4 hexadecimal digits (with possible leading zeroes), compress the address according to the following rules:

  • Remove any leading zeroes from each 16-bit group.
  • Find the longest consecutive sequence of groups that are equal to 0 (after removing leading zeros) and replace that entire sequence with a double colon ::. If there are multiple sequences of the same length, compress the first one found.
  • The double colon :: can appear at most once.
  • If no compression is possible, output the address in its original form (except that leading zeros in each group should still be removed).

Note: This compression style is similar to the default display on macOS (Darwin). For example:

  • 2001:0db8:0000:0000:0123:4567:89ab:cdef compresses to 2001:db8::123:4567:89ab:cdef.
  • 2001:0db8:0000:0000:1:0000:0000:0000 compresses to 2001:db8:0:0:1::.
  • 2001:0db8:ffff:0000:0123:4567:89ab:cdef compresses to 2001:db8:ffff::123:4567:89ab:cdef.

Write a program that reads a fully expanded IPv6 address (with no occurrences of :: in the input) and outputs its compressed form.

inputFormat

The input consists of a single line containing a fully expanded IPv6 address. The IPv6 address is eight groups of exactly 4 hexadecimal digits, separated by colons. There are no occurrences of :: in the input.

outputFormat

Output the compressed IPv6 address according to the rules described above.

sample

2001:0db8:0000:0000:0123:4567:89ab:cdef
2001:db8::123:4567:89ab:cdef