A Pie for a Pie
Time limit2sMemory limit512 MB
Each cow alternately returns a pie whose own tastiness is within D above the received pie; for each of Bessie's pies, find the fewest pies in an exchange ending with a zero-valued pie.
- Level
Hard8 of 10
- Topics
- Graph, BFS, Sorting, Binary search
- Solved
- No attempts yet
Problem
Bessie and Elsie have each baked pies (). Every one of the pies has a tastiness value according to Bessie and a tastiness value according to Elsie, and the two values may differ.
Bessie is thinking about giving one of her pies to Elsie. If Elsie receives a pie from Bessie, she feels obliged to hand back one of her own pies. So as to look neither stingy nor extravagant, Elsie picks a pie that in her own eyes is at least as tasty as the pie she received but no more than units tastier (). If no such pie exists, Elsie gives up and the exchange ends unhappily.
If Elsie does hand back a pie, Bessie then picks one of her own pies that in her own eyes is at least as tasty as the pie Elsie just gave her but no more than units tastier. If she has no such pie, Bessie gives up too and the exchange again ends unhappily. Otherwise she gives the chosen pie to Elsie, and the cycle repeats until one cow gives up or until a cow receives a pie she values at . Receiving a pie worth ends the exchange and both cows are happy.
A pie is never gifted twice, and neither cow hands back the pie she has just received.
For each of the pies Bessie could choose as her first gift, find the smallest number of pies that can change hands in a happy exchange.
Input
The first line contains two integers and .
Each of the next lines contains two space separated integers: the value of one pie according to Bessie, then the value of that same pie according to Elsie.
The first of those lines describe Bessie's pies and the remaining lines describe Elsie's pies.
Every tastiness value is in the range .
Output
Print lines. Line contains the smallest number of pies that can be gifted in a happy exchange that starts with Bessie's pie , counting that first gift. If no exchange that starts with pie ends happily, print on line instead.