import sugar, strutils, queues proc nextString: string = result = "" while not endOfFile stdin: let nextChar = readChar stdin case nextChar of '\r': discard of "\n"[0], ' ': break else: add result, nextChar proc nextInt: int = parseInt nextString() let n, driveCst = nextInt() TK = lc[(nextInt(), nextInt()) | (i <- 0 ..< n), tuple[tyo, kyo: int]] var earningsTyo, earningsKyo = lc[int.low | (i <- 0 .. n), int] proc bfs: int = var Q = initQueue[tuple[day, pool: int, place: char]]() enqueue Q, (0, 0, 't') while Q.len != 0: let q = dequeue Q if q.day == n: continue for p in ['t', 'k']: var poolNow = q.pool - driveCst * int(p != q.place) if p == 't': poolNow += TK[q.day].tyo if earningsTyo[q.day + 1] < poolNow: enqueue Q, (q.day + 1, poolNow, 't') earningsTyo[q.day + 1] = poolNow if p == 'k': poolNow += TK[q.day].kyo if earningskyo[q.day + 1] < poolNow: enqueue Q, (q.day + 1, poolNow, 'k') earningsKyo[q.day + 1] = poolNow max(earningsTyo[n], earningsKyo[n]) proc main: void = echo bfs() if isMainModule: main()