結果
問題 |
No.119 旅行のツアーの問題
|
ユーザー |
![]() |
提出日時 | 2025-06-12 16:54:05 |
言語 | PyPy3 (7.3.15) |
結果 |
AC
|
実行時間 | 1,265 ms / 5,000 ms |
コード長 | 2,586 bytes |
コンパイル時間 | 934 ms |
コンパイル使用メモリ | 82,560 KB |
実行使用メモリ | 255,792 KB |
最終ジャッジ日時 | 2025-06-12 16:54:10 |
合計ジャッジ時間 | 4,437 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 4 |
other | AC * 19 |
ソースコード
import sys from collections import defaultdict def main(): N = int(sys.stdin.readline()) B = [] C = [] for _ in range(N): b, c = map(int, sys.stdin.readline().split()) B.append(b) C.append(c) M = int(sys.stdin.readline()) constraints = [[] for _ in range(N)] for _ in range(M): D, E = map(int, sys.stdin.readline().split()) constraints[D].append(E) # Initialize DP: dictionary where key is mask, value is max satisfaction dp = {0: 0} for i in range(N): next_dp = defaultdict(int) for mask, current_max in dp.items(): # Option 1: do not include i if mask in next_dp: if current_max > next_dp[mask]: next_dp[mask] = current_max else: next_dp[mask] = current_max # Option 2: include i if (mask >> i) & 1: # Must take the tour new_mask = mask for e in constraints[i]: new_mask |= (1 << e) new_sat = current_max + B[i] if new_mask in next_dp: if new_sat > next_dp[new_mask]: next_dp[new_mask] = new_sat else: next_dp[new_mask] = new_sat else: # Option a: take the tour new_mask_a = mask for e in constraints[i]: new_mask_a |= (1 << e) new_sat_a = current_max + B[i] if new_mask_a in next_dp: if new_sat_a > next_dp[new_mask_a]: next_dp[new_mask_a] = new_sat_a else: next_dp[new_mask_a] = new_sat_a # Option b: do not take the tour new_mask_b = mask new_sat_b = current_max + C[i] if new_mask_b in next_dp: if new_sat_b > next_dp[new_mask_b]: next_dp[new_mask_b] = new_sat_b else: next_dp[new_mask_b] = new_sat_b # Update dp to next_dp, keeping only the maximum for each mask dp = {} for mask in next_dp: if mask in dp: if next_dp[mask] > dp[mask]: dp[mask] = next_dp[mask] else: dp[mask] = next_dp[mask] if dp: print(max(dp.values())) else: print(0) if __name__ == '__main__': main()