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 :


                            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

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →