IPvX
Time limit2sMemory limit1024 MB
Given taken IPvX addresses and starting addresses a < b, find the fewest addresses to occupy so the two assigned addresses become adjacent, or -1.
- Level
Medium7 of 10
- Topics
- Implementation, Hash map, Greedy
- Solved
- No attempts yet
Statement
Jumanji is an interactive game, so almost anything can happen in it. This time our heroes took a wrong turn and were captured by Doctor DHCP, the chief cyber-scientist villain of Jumanji. The heroes do not interest the Doctor, so he will let them go if they help with a problem that has resisted him for several days.
Doctor DHCP has computers in his lab, and the -th one has IPvX address . An IPvX address is a regular IPv4 address with one change: it has groups instead of 4. So each address has the form , where every is between 0 and 255 inclusive. Addresses are ordered as follows: is less than if for some , , , and .
In this problem, the next address is the smallest address greater than the current one, and the previous address is the largest address less than the current one. For example, the next address after is , after it is , and after it is .
Doctor DHCP wants to add two new computers to his local network. The network assigns IPvX addresses as follows. The first computer first receives address . While this address is taken, it switches to the next address, if one exists. After the first computer gets its address, the second computer receives address and follows a similar procedure: if its current address is taken, it tries the previous address, if one exists, and so on.
The goal is that after both computers receive their addresses, the address of the second computer is the next address after the address of the first computer. This is not always possible, so the Doctor has added fictitious occupation: he can send a request to the local network to occupy any address. That address then counts as taken, even though no computer owns it. The Doctor dislikes this operation and wants to use it as few times as possible.
Given and , find the minimum number of fictitious occupations needed so that, after both computers receive addresses, the two addresses are adjacent. If it is impossible, print .
Input
The first line has and (, ). Each of the next lines gives the address of one computer in the form (). Lines and contain the initial addresses and of the first and second computers, in the same format. All computer addresses are pairwise distinct, and is less than .
Output
Print the minimum number of fictitious occupations, or if it cannot be done.
Hint
In the first test, occupying address 123.123.123.124 is enough. Then the computers take addresses 123.123.123.121 and 123.123.123.122. The test cases in the statement do not belong to the first test group, but they must pass to be accepted.