ครั้งก่อน Feedback ไม่ค่อยดี (จริงๆแล้วไม่มี feedback - -‘’) เลยตัดสินใจเลิกเขียนอธิบายดีกว่า เมื่อยตุ้ม 55+
โจทย์ที่นี่ (Qualification Round 2008)
จุดเน้น : ข้อนี้มันออกแนวๆ Simulation มากกว่านะ คือจำลองเหตุการณ์ตามที่กำหนดให้ไปเรื่อยๆ แล้วบันทึกค่าไว้เป็นคำตอบ โค้ดไม่ยาวเท่าไหร่ แต่ดีบักอยู่หลายชม. ไม่เคยเขียนนี่หว่า - -‘ จบข้อนี้ได้ความรู้ Python ใหม่ๆ ได้แก่
- ลองใช้ List Comprehension เพิ่มเติม
- ลองใช้ Lambda กับ map, filter, reduce และ list.sort
class Event(object):
def __init__(self):
# Time in seconds
self.time = 0
# Offset to apply to train count
self.offset = (0,0)
if __name__ == '__main__':
#in_filename = "B-small-practice.in"
in_filename = "B-large-practice.in"
#out_filename = "B-small.out"
out_filename = "B-large.out"
in_file = open(in_filename, 'r')
num_cases = int(in_file.readline())
out_file = open(out_filename, 'w')
for c in range(0,num_cases):
turnaround = int(in_file.readline())
from_a, from_b = [int(x) for x in in_file.readline().split(' ')]
actions = []
for a in range(0,from_a):
# Get departure/arrival time in minutes
depart, arrive = [reduce(lambda h,m : h*60 + m,[ int(y) for y in x.split(':') ]) for x in in_file.readline().split(' ')]
# Departure event : A--
ev = Event()
ev.time = depart
ev.offset = -1,0
actions.append(ev)
# Ready for next departure : B++
ev = Event()
ev.time = arrive + turnaround
ev.offset = 0,1
actions.append(ev)
for b in range(0,from_b):
# Get departure/arrival time in minutes
depart, arrive = [reduce(lambda h,m : h*60 + m,[ int(y) for y in x.split(':') ]) for x in in_file.readline().split(' ')]
# Departure event : B--
ev = Event()
ev.time = depart
ev.offset = 0,-1
actions.append(ev)
# Ready for next departure : A++
ev = Event()
ev.time = arrive + turnaround
ev.offset = 1,0
actions.append(ev)
# Sort the events by their times
actions.sort(cmp=lambda x,y : cmp(x.time,y.time))
train_count_a, train_count_b = 0,0
lowest_a, lowest_b = 0,0
last_time = None
for act in actions:
if last_time != act.time:
# Only track the lowest values when all events
# at the same time are all processed
lowest_a = min(lowest_a, train_count_a)
lowest_b = min(lowest_b, train_count_b)
last_time = act.time
#print act.time,act.offset
train_count_a = train_count_a + act.offset[0]
train_count_b = train_count_b + act.offset[1]
#l = raw_input("pause ..")
out_file.write("Case #%d: %d %d\n" % (c+1,lowest_a*-1, lowest_b*-1))
out_file.close()
Tags: algorithm, google, code jam