Railway Tickets
Time limit1sMemory limit256 MB
Count station pairs where every leg has a free seat but no single seat stays free for the whole trip.
- Level
Medium6 of 10
- Topics
- Intervals, Sorting, Prefix sum
- Solved
- No attempts yet
Problem
Long distance trains sell one reserved seat per ticket. A passenger knows in advance that a seat is waiting, but the rule makes free seats look sold out.
Consider a train with two seats that runs from station A to station C and stops once at station B. Seat 1 is sold for A to B, and seat 2 is sold for B to C. No single seat is free for the whole trip from A to C. A traveler can still buy seat 2 for A to B and seat 1 for B to C, then change seats at station B.
Call the stretch of the route between two neighbouring stations a leg. Given the tickets that are already sold, count the pairs of a departure station and an arrival station that can be travelled only by buying two or more tickets and changing seats on the way. Any seat that is not sold on a leg can be bought.
The exact condition is this. For two stations , the trip from to is possible when every leg between them has at least one free seat. The pair is counted when the trip is possible and no single seat is free on all of the legs from to at once.
Input
The first line contains the number of seats in the train (). The second line contains the number of stations on the route (). The third line contains the number of tickets already sold ().
Each of the next lines contains three integers , , describing one ticket. is the number of the reserved seat; seats are numbered from to over the whole train, without splitting by carriage. and are the departure and the arrival station; stations are numbered from to along the route. Every ticket has . One seat can carry several tickets, but their ranges do not overlap: the next ticket for a seat starts at the station where the previous one ends, or later on the route.
Output
Print one integer, the number of station pairs.
Notes
The ten pairs in the example are , , , , , , , , and . For every other pair, either one direct ticket with a reserved seat is available, or some leg has no free seat, so the trip is impossible even for a passenger who buys several tickets and changes seats.