Minimum Average Waiting Time


Problem Statement :


Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes.

Different kinds of pizzas take different amounts of time to cook. Also, once he starts cooking a pizza, he cannot cook another pizza until the first pizza is completely cooked. Let's say we have three customers who come at time t=0, t=1, & t=2 respectively, and the time needed to cook their pizzas is 3, 9, & 6 respectively. If Tieu applies first-come, first-served rule, then the waiting time of three customers is 3, 11, & 16 respectively. The average waiting time in this case is (3 + 11 + 16) / 3 = 10. This is not an optimized solution. After serving the first customer at time t=3, Tieu can choose to serve the third customer. In that case, the waiting time will be 3, 7, & 17 respectively. Hence the average waiting time is (3 + 7 + 17) / 3 = 9.

Help Tieu achieve the minimum average waiting time. For the sake of simplicity, just find the integer part of the minimum average waiting time.

Input Format

The first line contains an integer N, which is the number of customers.
In the next N lines, the ith line contains two space separated numbers Ti and Li. Ti is the time when ith customer order a pizza, and Li is the time required to cook that pizza.

The ith customer is not the customer arriving at the ith  arrival time.

Output Format

Display the integer part of the minimum average waiting time.
Constraints

1 ≤ N ≤ 105
0 ≤ Ti ≤ 109
1 ≤ Li ≤ 109
Note

The waiting time is calculated as the difference between the time a customer orders pizza (the time at which they enter the shop) and the time she is served.

Cook does not know about the future orders.



Solution :



title-img


                            Solution in C :

In C ++ :





#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <iostream>
#include <set>
#include <vector>
#include <cstring>
#include <string>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <complex>
#include <map>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
typedef pair<double, double> pdd;
typedef vector<pll> vll;
typedef vector<string> vs;

int main() {
    int n;
    cin >> n;
    vll v(n);
    for (int i = 0; i < n; ++i) {
        scanf("%lld%lld", &v[i].first, &v[i].second);        
    }
    sort(v.begin(), v.end());
    ll sum = 0;
    set<pii> q;
    ll t = v[0].first;
    int it = 0;
    while (it < n || q.size()) {
        while (it < n && v[it].first <= t) {
            q.insert(pii(v[it].second, it));
            ++it;
        }
        if (q.empty()) {
            t = v[it].first;
        } else {
            int i = q.begin()->second;
            q.erase(q.begin());
            t += v[i].second;
            sum += t-v[i].first;
        }
    }
    cout << sum / n << endl;
    return 0;
}









In Java :





import java.util.*;
import java.io.*;

public class Solution {

    static void go() {
        int n = in.nextInt();
        Customer[] c = new Customer[n];
        for(int i = 0; i < n; i++) {
            c[i] = new Customer(in.nextInt(), in.nextInt());
        }
        Arrays.sort(c, Customer.Order.ByT.ascending());

        PriorityQueue<Customer> q =
                new PriorityQueue<Customer>(n, Customer.Order.ByL.ascending());
        long time = c[0].t;
        int idx = 0;
        while(idx < n && c[idx].t <= time) {
            q.add(c[idx]);
            idx++;
        }

        long wait = 0;
        while(q.size() > 0) {
            Customer next = q.poll();
            time += next.l;
            wait += time - next.t;

            if (idx < n && q.size() == 0 && time < c[idx].t) {
                time = c[idx].t;
            }
            while(idx < n && c[idx].t <= time) {
                q.add(c[idx]);
                idx++;
            }
        }
        out.println(wait / n);
    }

    public static class Customer {
        public Long t, l;
        public Customer(long t1, long l1) {this.t = t1; this.l = l1;}

        public static enum Order implements Comparator<Customer> {
            ByT() {
                public int compare(Customer c1, Customer c2) {
                    return c1.t.compareTo(c2.t);
                }
            },
            ByL() {
                public int compare(Customer c1, Customer c2) {
                    return c1.l.compareTo(c2.l);
                }
            };

            public abstract int compare(Customer c1, Customer c2);

            public Comparator ascending() {
                return this;
            }

            public Comparator descending() {
                return Collections.reverseOrder(this);
            }
        }
    }

    static InputReader in;
    static PrintWriter out;

    public static void main(String[] args) {
        in = new InputReader(System.in);
        out = new PrintWriter(System.out);

        go();

        out.close();
    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            return (int) nextLong();
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String nextString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder sb = new StringBuilder(1024);
            do {
                sb.append((char) c);
                c = read();
            } while (!isSpaceChar(c));
            return sb.toString();
        }

        public static boolean isSpaceChar(int c) {
            switch (c) {
                case -1:
                case ' ':
                case '\n':
                case '\r':
                case '\t':
                    return true;
                default:
                    return false;
            }
        }
    }
}









In C :






#include<stdio.h>
unsigned int Heap[100001],Index[100001],Position[100001],Size=0;
unsigned int Temp[100001],Temp1[100001];
unsigned int Arr_Time[100001],Cook_Time[100001],Num;
void merge(int Low,int Mid,int High)
{

   int i=Low,j=Mid+1,k=0;
  
 
   while(i<=Mid&&j<=High)
   {
   if(Arr_Time[i]<=Arr_Time[j])
   {
     Temp[k]=Arr_Time[i];
     Temp1[k]=Cook_Time[i];     
     i++;
     k++;
    
   }
   else
   {
     Temp[k]=Arr_Time[j];
     Temp1[k]=Cook_Time[j];      
     j++;
     k++;
   }
  }
  if(i<=Mid)
  {
    int I;
    for(I=i;I<=Mid;I++)
    {Temp[k]=Arr_Time[I];     Temp1[k]=Cook_Time[I];k++;}
  }
  else if(j<=High)
  {
    int I;
    for(I=j;I<=High;I++)
    {Temp[k]=Arr_Time[I];     Temp1[k]=Cook_Time[I];k++;}
  }
  k=0;
  for(i=Low;i<=High;i++)
  {
    
   
     Arr_Time[i]=Temp[k];
     Cook_Time[i]=Temp1[k];
     k++;
  }
  
}
void divide(int Low,int High)
{
  if(Low<High)
  {
     int Mid=(Low+High)/2;
  
     divide(Low,Mid);
     divide(Mid+1,High);
     merge(Low,Mid,High);
  }  
}

void Insert(int Node,unsigned int Value)
{
     int S;
     if(Position[Node]==0)
     {
      Heap[++Size]=Value;
      Index[Size]=Node;
      Position[Node]=Size;
      S=Size;
     }
     else 
     {
       Heap[Position[Node]]=Value;
       S=Position[Node];
     }
     while(S!=1)
     {
         if(Heap[S/2]>Heap[S])
         {
             int t=Heap[S/2];
             Heap[S/2]=Heap[S];
             Heap[S]=t;
             
             t=Index[S/2];
             Index[S/2]=Index[S];
             Index[S]=t;
             
             Position[Index[S/2]]=S/2;
             Position[Index[S]]=S;
         }
         else
         break;
         S=S/2;
     }
     
}
int Extract_Min()
{
    int N=Index[1];
    int S=1;
    
 //   printf("%d\n",Heap[1]);
    Position[N]=-1;
    Index[1]=Index[Size];
    Position[Index[Size]]=1;
    Heap[1]=Heap[Size--];
    while(1)
    {
        int T;
        if(Heap[S*2]<Heap[S]&&S*2<=Size||Heap[S*2+1]<Heap[S]&&S*2+1<=Size)
        {
          if(Heap[S*2]<Heap[S*2+1])
          T=S*2;
          else 
          T=S*2+1;
          
           int t=Heap[T];
           Heap[T]=Heap[S];
           Heap[S]=t;
             
           t=Index[T];
           Index[T]=Index[S];
           Index[S]=t;
             
           Position[Index[T]]=T;
           Position[Index[S]]=S;
        }
        else
        break;
        S=T;
    }
   
    return N;
}
void Init(int N)
{
  int i;
  for(i=1;i<=N;i++)
  {
    Position[i]=0;
    Index[i]=0;
    Heap[i]=1000000001;
  }
  Size=N;
}    
int main()
{
    int A_T,C_T,i=1;
    
    long long Wait_Time=0,Time=0;
    scanf("%d",&Num);
    //init(N);
for(i=0;i<Num;i++)
scanf("%u%u",&Arr_Time[i],&Cook_Time[i]);
divide(0,Num-1);
for(i=Num;i>=1;i--)
{
                   Arr_Time[i]=Arr_Time[i-1];
Cook_Time[i]=Cook_Time[i-1];
//printf("%u %u\n",Arr_Time[i],Cook_Time[i]);
}
Insert(1,Cook_Time[1]); 

i=2;
          while(i<=Num&&Arr_Time[i]==Arr_Time[1])
          {
           Insert(i,Cook_Time[i]);  
           i++;
          }
        
    while(Size!=0)
    {
          int I=Extract_Min();
          if(Time>Arr_Time[I])
          {
           Wait_Time+=Time-Arr_Time[I]+Cook_Time[I];                   
           Time+=Cook_Time[I];
           // printf("%d %d %d \n",I,Time,Wait_Time);
          }
          else
          {
              Time=Arr_Time[I]+Cook_Time[I];
              Wait_Time+=Cook_Time[I];
          }
        //  printf("%d %lld %lld \n",I,Time,Wait_Time);
          I=i;
          while(i<=Num&&Arr_Time[i]<=Time)          
          {
          Insert(i,Cook_Time[i]);  
          i++;
          }
          if(I==i&&i<=Num)//No job is before curr_time
          {
            Insert(i,Cook_Time[i]); 

            i++;
          while(i<=Num&&Arr_Time[i]==Arr_Time[I])
          {
           Insert(i,Cook_Time[i]);  
           i++;
          }          
          }
    }
    Wait_Time=Wait_Time/Num;
    printf("%lld",Wait_Time);
   // system("pause");
    return 0;
}








In Python3 :






import queue
pre_orders = []
last_order = None
cases = int(input())
available = queue.PriorityQueue(cases)
total_wait = 0

for _ in range(cases):
    pre_orders.append ([int(x) for x in input().split()])
    
pre_orders.sort(key=lambda x: x[0], reverse=True)

last_order = pre_orders.pop()
last_order.append(last_order[0] + last_order[1])
total_wait += last_order[2] - last_order[0]

time = last_order[2]
for _ in range(cases-1):
                        
    while(pre_orders and time >= pre_orders[-1][0]): 
        node = pre_orders.pop()
        available.put((node[1], node))
                        
    if available:
        deleted = available.get()[1]
        deleted.append(time + deleted[1])
        total_wait += deleted[2] - deleted[0]
        last_order = deleted
    else:
        temp = pre_orders.pop()
        temp.append(temp[0] + temp[1])
        total_wait += temp[2] - temp[0]
        last_order = temp

    time = last_order[2]

    
print(int(total_wait/cases))
                        








View More Similar Problems

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →