Skip to content

Commit

Permalink
add Leetcode Biweekly Contest 29
Browse files Browse the repository at this point in the history
  • Loading branch information
Wizmann committed Aug 23, 2020
1 parent d538f2c commit 8772a0e
Show file tree
Hide file tree
Showing 4 changed files with 121 additions and 0 deletions.
75 changes: 75 additions & 0 deletions Leetcode/Algorithm/cpp/Parallel Courses II.cc
@@ -0,0 +1,75 @@
const int INF = 0x3f3f3f3f;

class Solution {
public:
int minNumberOfSemesters(int n, vector<vector<int>>& dependencies, int k) {
vector<int> dis(1 << n, INF);
vector<vector<int> > g(n);
vector<int> ind(n, 0);
for (const auto& v: dependencies) {
int a = v[0] - 1;
int b = v[1] - 1;
g[a].push_back(b);
ind[b]++;
}

queue<int> q;
q.push(0);
dis[0] = 0;
vector<int> curind(n);
vector<int> candidates(n);

while (!q.empty()) {
int cur = q.front();
q.pop();
if (cur == (1 << n) - 1) {
break;
}
curind = ind;
for (int i = 0; i < n; i++) {
if ((cur & (1 << i)) == 0) {
continue;
}
for (auto nxt: g[i]) {
curind[nxt]--;
}
}

candidates.clear();
for (int i = 0; i < n; i++) {
if (!(cur & (1 << i)) && curind[i] == 0) {
candidates.push_back(i);
}
}

int m = candidates.size();
if (m < k) {
int nxt = cur;
for (auto c: candidates) {
nxt |= 1 << c;
}
if (dis[nxt] >= INF) {
dis[nxt] = dis[cur] + 1;
q.push(nxt);
}
} else {
for (int i = 0; i < (1 << m); i++) {
if (__builtin_popcount(i) != k) {
continue;
}
int nxt = cur;
for (int j = 0; j < m; j++) {
if (i & (1 << j)) {
nxt |= 1 << (candidates[j]);
}
}
if (dis[nxt] >= INF) {
dis[nxt] = dis[cur] + 1;
q.push(nxt);
}
}
}
}
return dis[(1 << n) - 1];
}
};
@@ -0,0 +1,4 @@
class Solution(object):
def average(self, salary):
tot = sum(salary) - min(salary) - max(salary)
return 1.0 * tot / (len(salary) - 2)
@@ -0,0 +1,33 @@
class Solution(object):
def longestSubarray(self, nums):
n = len(nums)
dp1 = [-1 for i in xrange(n)]
dp2 = [-1 for i in xrange(n)]

pre = 0
for i in xrange(n):
if nums[i] == 1:
pre += 1
dp1[i] = pre
else:
pre = 0
dp1[i] = pre
pre = 0
for i in xrange(n - 1, -1, -1):
if nums[i] == 1:
pre += 1
dp2[i] = pre
else:
pre = 0
dp2[i] = pre
# print dp1
# print dp2
res = 0
for i in xrange(n):
tot = 0
if i - 1 >= 0:
tot += dp1[i - 1]
if i + 1 < n:
tot += dp2[i + 1]
res = max(res, tot)
return res
9 changes: 9 additions & 0 deletions Leetcode/Algorithm/python/The kth Factor of n.py
@@ -0,0 +1,9 @@
class Solution(object):
def kthFactor(self, n, k):
cnt = 0
for i in xrange(1, n + 1):
if n % i == 0:
cnt += 1
if cnt == k:
return i
return -1

0 comments on commit 8772a0e

Please sign in to comment.