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
Subsequence Weighting
A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =
View Solution →Kindergarten Adventures
Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti
View Solution →Mr. X and His Shots
A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M
View Solution →Jim and the Skyscrapers
Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space
View Solution →Palindromic Subsets
Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t
View Solution →Counting On a Tree
Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n
View Solution →