- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 65 lines of C++ from the credited upstream file minimum-time-to-transport-all-individuals.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 5 loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 double minTime(int n, int k, int m, vector<int>& time, vector<double>& mul) {8 static const auto INF = numeric_limits<double>::max();9 10 vector<int> lookup(1 << n);11 for (int mask = 1; mask < 1 << n; ++mask) { 12 for (int i = 0; i < n; ++i) {13 if (!(mask & (1 <<i))) {14 continue;15 }16 lookup[mask] = max(lookup[mask], time[i]);17 }18 }19 20 vector<vector<vector<double>>> dist(2, vector<vector<double>>(m, vector<double>(1 << n, INF)));21 dist[0][0][(1 << n) - 1] = 0.0;22 using D = tuple<double, int, int, int>;23 priority_queue<D, vector<D>, greater<D>> min_heap;24 min_heap.emplace(0.0, 0, 0, (1 << n) - 1);25 const auto& update = [&](double d, int r, int s, int mask, int submask) {26 const auto& t = lookup[submask] * mul[s];27 const auto& nr = r ^ 1;28 const auto& ns = (s + static_cast<int>(t)) % m;29 const auto& new_mask = mask ^ submask;30 const auto& nd = d + t;31 if (dist[nr][ns][new_mask] > nd) {32 dist[nr][ns][new_mask] = nd;33 min_heap.emplace(nd, nr, ns, new_mask);34 }35 };36 37 while (!empty(min_heap)) {38 const auto [d, r, s, mask] = min_heap.top(); min_heap.pop(); 39 if (d != dist[r][s][mask]) {40 continue;41 }42 if (mask == 0) {43 assert(r == 1);44 return d;45 }46 if (r == 0) {47 for (int submask = mask; submask; submask = (submask - 1) & mask) { 48 if (__builtin_popcount(submask) > k) {49 continue;50 }51 update(d, r, s, mask, submask);52 }53 } else {54 for (int i = 0; i < n; ++i) { 55 if (mask & (1 << i)) {56 continue;57 }58 update(d, r, s, mask, 1 << i);59 }60 }61 }62 return -1.0;63 }64};65