Find the cheapest path that visits all Holsteins in order and all Guernseys in order, starting at Holstein 1 and ending at Holstein H.
Medium6Dynamic programmingGeometryInterviewNo attempts yetTime limit2sMemory limit512 MBEvery day Farmer John walks through his pasture and checks on each of his cows. He keeps two breeds, Holsteins and Guernseys. His H Holsteins are numbered 1 to H, and his G Guernseys are numbered 1 to G (1≤H≤1000, 1≤G≤1000). Each cow stands at a point in the 2D plane, and two cows may stand at the same point.
Farmer John starts his tour at Holstein 1 and finishes it at Holstein H. He visits every cow exactly once along the way, and to keep his checklist easy to fill in he visits the cows of each breed in increasing order of their numbers. In the sequence of all H+G cows he visits, Holsteins 1 to H appear as a subsequence that need not be contiguous, and the Guernseys appear the same way. Put differently, the whole visiting order is one interleaving of the list of Holsteins with the list of Guernseys.
Moving from one cow to another cow over a distance of D costs D2 energy. Find the smallest amount of energy a tour that obeys these rules needs.
The first line contains H and G, separated by a space.
Each of the next H lines contains the x and y coordinates of a Holstein, in order of their numbers. Each of the following G lines contains the coordinates of a Guernsey, in order of their numbers. Every coordinate is an integer between 0 and 1000. The input always admits at least one tour that obeys the rules.
Print the minimum energy needed to visit all the cows on a single line. The total energy is always an integer.