File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
solution/3500-3599/3530.Maximum Profit from Valid Topological Order in DAG Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int maxProfit (int n, vector<vector<int >>& edges, vector<int >& score) {
4
+ vector<int > prereq (n, 0 );
5
+ for (auto &e : edges) {
6
+ int u = e[0 ], v = e[1 ];
7
+ prereq[v] |= (1 << u);
8
+ }
9
+
10
+ int N = 1 << n;
11
+ vector<int > dp (N, INT_MIN);
12
+ dp[0 ] = 0 ;
13
+
14
+ for (int mask = 0 ; mask < N; ++mask) {
15
+ if (dp[mask] < 0 ) continue ;
16
+ int pos = __builtin_popcount (mask) + 1 ;
17
+ int free = (~mask) & (N - 1 );
18
+ for (int i = 0 ; i < n; ++i) {
19
+ if ((free & (1 << i))
20
+ && (mask & prereq[i]) == prereq[i]) {
21
+ int m2 = mask | (1 << i);
22
+ dp[m2] = max (dp[m2], dp[mask] + score[i] * pos);
23
+ }
24
+ }
25
+ }
26
+
27
+ return dp[N - 1 ];
28
+ }
29
+ };
You can’t perform that action at this time.
0 commit comments