Skip to content

Instantly share code, notes, and snippets.

@Kulbear
Created September 4, 2017 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kulbear/eee19a365e6ffc11e60a5c5aaa9128d0 to your computer and use it in GitHub Desktop.
Save Kulbear/eee19a365e6ffc11e60a5c5aaa9128d0 to your computer and use it in GitHub Desktop.
# Uses python3
import sys
from collections import namedtuple
Segment = namedtuple('Segment', 'start end')
def optimal_points(segments):
points = []
segments_by_end = sorted(segments, key=lambda x: x.end)
segments_by_start = sorted(segments, key=lambda x: x.start)
while len(segments_by_end) > 0:
seg = segments_by_end[0]
i = 0
# Loop through all points in segments_by_start
# if the start point is on the left (or equal)
# remove it from both list
while i < len(segments_by_start):
if segments_by_start[i].start <= seg.end:
segments_by_end.remove(segments_by_start[i]) # remove it from this list first
segments_by_start.remove(segments_by_start[i])
else:
i += 1
points.append(seg.end)
return list(set(points))
if __name__ == '__main__':
input = sys.stdin.read()
n, *data = map(int, input.split())
segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2])))
points = optimal_points(segments)
print(len(points))
for p in points:
print(p, end=' ')
Input
3
1 3
2 5
3 6
Ouput
1
3
Input
4
4 7
1 3
2 5
5 6
Output
2
3 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment