ABC103D As shown in the figure below, the question is how many pieces are required to skewer everything. The interval scheduling problem is as follows:
Given M intervals, choose the maximum number of intervals so that no two intervals share a time zone
It's a well-known problem at the beginning of the Greedy chapter of the ant book, and you can sort it at the end of the section and take it to Greedy.
In fact, the answer to this question is the same as the optimal solution for the interval scheduling problem:
On the contrary, the fact that k skewers are sufficient can be understood by carefully following the movement of the greedy algorithm for the interval scheduling problem. In particular,
Sample code
from operator import itemgetter
n, m = map(int, input().split())
#Sort at the end of the interval
ab = sorted([tuple(map(int, input().split())) for i in range(m)], key=itemgetter(1))
#The bridge that was removed last time
removed = -1
ans = 0
for a, b in ab:
#a is greater than removed=I haven't removed it yet
if a > removed:
removed = b - 1
ans += 1
print(ans)
Recommended Posts