Skip to content

Commit dbe8616

Browse files
committed
Added c++ code for 3500-3599-/-3530.-Maximum-Profit-from-Valid-Topological-Order-in-DAG
1 parent f9e3720 commit dbe8616

File tree

1 file changed

+29
-0
lines changed
  • solution/3500-3599/3530.Maximum Profit from Valid Topological Order in DAG

1 file changed

+29
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
};

0 commit comments

Comments
 (0)