fork download
  1. import sys
  2. import bisect
  3.  
  4. def main():
  5. data = sys.stdin.read().strip().split()
  6. if not data:
  7. return
  8. it = iter(data)
  9. n = int(next(it))
  10. jobs = []
  11. for idx in range(n):
  12. s = int(next(it)); e = int(next(it)); w = int(next(it))
  13. # store original index (1-based), start, end, weight
  14. jobs.append((idx + 1, s, e, w))
  15.  
  16. # stable sort by end time
  17. jobs.sort(key=lambda x: x[2]) # Python's sort is stable
  18.  
  19. # prepare arrays (1-based for DP)
  20. ends = [job[2] for job in jobs] # 0-based list of end times
  21. v = [0] * (n + 1) # weights, 1-based
  22. s = [0] * (n + 1) # start times, 1-based
  23. # p[j] = largest index i (0..j-1) such that end_i <= start_j; using 1-based, p in [0..n]
  24. p = [0] * (n + 1)
  25. for j in range(1, n + 1):
  26. _, sj, ej, wj = jobs[j-1]
  27. s[j] = sj
  28. v[j] = wj
  29. # bisect_right returns count of ends <= sj
  30. p[j] = bisect.bisect_right(ends, sj)
  31.  
  32. # DP compute OPT
  33. OPT = [0] * (n + 1)
  34. for j in range(1, n + 1):
  35. include = v[j] + OPT[p[j]]
  36. exclude = OPT[j-1]
  37. OPT[j] = max(exclude, include)
  38.  
  39. # Reconstruct solution following the rule:
  40. # if OPT[j-1] >= v[j] + OPT[p[j]] then exclude (skip), else include
  41. solution = []
  42. j = n
  43. while j > 0:
  44. if OPT[j-1] >= v[j] + OPT[p[j]]:
  45. j -= 1
  46. else:
  47. # include job j (its position after sorting)
  48. solution.append(j)
  49. j = p[j]
  50.  
  51. # Output requires descending order
  52. solution.sort(reverse=True)
  53. print(solution)
  54.  
  55. if __name__ == "__main__":
  56. main()
  57.  
Success #stdin #stdout 0.1s 14036KB
stdin
10
3 9 2
5 6 3
1 10 4
4 5 3
6 13 5
4 8 5
3 19 8
6 16 6
9 11 4
3 8 6
stdout
[9, 2, 1]