eolymp
bolt
Try our new interface for solving problems
Problems

Rube Goldberg Device

Rube Goldberg Device

Little Lucy's science project is really giving her a hard time. Her project requires that she build a Rube Goldberg device. A Rube Goldberg device is a device that performs a simple task in a convoluted way. In Lucy's case, she will be performing a series of energy transfers using a variety of parts. Each part will be formatted as "**INPUT OUTPUT TIME**", where INPUT is the type of energy required to start the part, OUTPUT is the type of energy released once the part has done its job, and TIME is the amount of time (in seconds) that the part takes to do its job. Lucy's parts have four different types of energy available: "CHEMICAL", "ELECTRIC", "MECHANICAL", and "THERMAL".

Lucy is going to put several of these devices in series to make a device that will run as close to target seconds as possible. The device will only work if the output from one part can be used as the input to the subsequent part. She can use any type of energy to start her machine, but she must use some part that releases last energy to complete the machine.

Given that Lucy has an infinite supply of each type of part, find the minimum absolute difference between the target time and the time that Lucy's machine operates.

Input

The first line of each test case contains the number of energy transfers n (1n50), and the values of target and last (1target, TIME250000). Next n lines describe the tranfers formated as “**INPUT OUTPUT TIME**”.

Output

For each test case print in a separate line the minimum absolute difference between the target time and the time that Lucy's machine operates.

Time limit 1 second
Memory limit 64 MiB
Input example #1
1 12 CHEMICAL
CHEMICAL CHEMICAL 5
3 123 THERMAL
CHEMICAL THERMAL 6
THERMAL CHEMICAL 3
THERMAL CHEMICAL 5
3 123456 ELECTRIC
CHEMICAL MECHANICAL 12
MECHANICAL THERMAL 13
THERMAL CHEMICAL 14
Output example #1
2
0
123456