Completion Order with Concurrency Limit
JavaScript
Hard
4 views
Problem Description
You have n task durations and limit k. Start first k tasks. When one finishes, start next. Print total time in first line, and completion order of task indices (1-based) in second line.
Input Format
Line1: n k. Line2: n integers durations.
Output Format
Line1: totalTime. Line2: completionOrder.
Official Solution
const fs=require('fs');const raw=fs.readFileSync(0,'utf8').trim();if(!raw)process.exit(0);const a=raw.split(/\\s+/).map(Number);let i=0;const n=a[i++];const k=a[i++];let d=a.slice(i,i+n);const heap=[];const push=x=>{heap.push(x);let p=heap.length-1;while(p>0){let q=(p-1)>>1;if(heap[q][0]<=heap[p][0])break;[heap[q],heap[p]]=[heap[p],heap[q]];p=q;}};const pop=()=>{const top=heap[0];const last=heap.pop();if(heap.length){heap[0]=last;let p=0;for(;;){let l=p*2+1,r=l+1,sm=p;if(l<heap.length && heap[l][0]<heap[sm][0])sm=l;if(r<heap.length && heap[r][0]<heap[sm][0])sm=r;if(sm===p)break;[heap[p],heap[sm]]=[heap[sm],heap[p]];p=sm;}}return top;};(async()=>{await Promise.resolve();let t=0;let next=0;let order=[];while(next<n && heap.length<k){push([d[next],next+1]);next++;}while(heap.length){const [fin,idx]=pop();t=fin;order.push(idx);if(next<n){push([t+d[next],next+1]);next++;}}process.stdout.write(String(t)+'\
'+order.join(' '));})();
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!