The story of Goldilocks and the three bears is well known. Much less known is that Goldilocks eventually took up farming. On her farm she has a barn holding N cows (1≤N≤20000), and those cows are sensitive to temperature.
Each cow i has a range of temperatures Ai through Bi that feels just right to it (0≤Ai≤Bi≤109). If Goldilocks sets the barn thermostat to a temperature T<Ai, cow i is too cold and produces X units of milk. If she sets it to a temperature with Ai≤T≤Bi, the cow is comfortable and produces Y units of milk. If she sets it to a temperature T>Bi, the cow is too hot and produces Z units of milk. Y is always larger than X and also larger than Z.
Given X, Y, Z and the preferred range of every cow, compute the maximum amount of milk Goldilocks can obtain when she sets the thermostat to the best possible value. X, Y and Z are integers between 0 and 1000, and the thermostat can be set to any integer value.
In the first example the barn holds four cows, whose preferred ranges are 5 through 8, 3 through 4, 13 through 20, and 7 through 10. A cold cow produces 7 units of milk, a comfortable cow produces 9, and a hot cow produces 6.
Setting the thermostat to 7 or to 8 leaves cows 1 and 4 comfortable, cow 2 too hot, and cow 3 too cold. The milk adds up to 31 units.