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

Minimum Average Waiting Time

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 h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →