French Dinner
Time limit2sMemory limit512 MB
Decide whether dishes can be assigned serving times satisfying simultaneity and precedence bounds while keeping the whole meal within K minutes.
- Level
Hard8 of 10
- Topics
- Shortest path, Graph, Math
- Solved
- No attempts yet
Problem

You are a French chef and you have to plan a very formal dinner. As a French chef you know every politeness rule the French apply to a meal: which items must be served at the same time, which must come first, how long to wait between courses.
For example, the red wine that goes with the cheese must be served at least five minutes before the cheese plate arrives, otherwise the guests cannot pick the cheese that suits the wine. That same wine has to arrive at least twenty minutes after the main course, so the guests have time to finish the wine served with the main course. The cheese must be served at about the same time as the bread, otherwise the guests eat the bread and the cheese separately. There are many more such rules, so many that you are not sure all of them can be satisfied.
You wrote every rule down, so now you can organize the perfect meal. Rules come in two kinds.
- A simultaneity rule SIM A B T means that A and B must be served at most minutes apart.
- A precedence rule BEF A B T means that A must be served at least minutes before B.
The meal must also take at most minutes in total, that is, at most minutes may pass between the first and the last item served. No dish may be skipped.
All bounds are inclusive. If A is served at and B at , then both SIM A B 1 and BEF A B 1 hold, and the meal made of A and B takes 1 minute.
Decide whether a schedule that satisfies every rule exists.
Input
The input has lines.
The first line has two integers and separated by a space. is the number of rules and is the largest duration allowed for the meal.
Each of the next lines holds one rule, of the form SIM A B T or of the form BEF A B T. Here is an integer, and A and B are non-empty strings of at most 1000 characters that contain no spaces. A rule may name the same dish twice.
Every integer in the input (, and each ) is between 0 and 1000 inclusive.
Output
Print one line containing YES if a meal that follows every rule can be organized, and NO otherwise.