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
Lazy White Falcon
White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi
View Solution →Ticket to Ride
Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o
View Solution →Heavy Light White Falcon
Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim
View Solution →Number Game on a Tree
Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy
View Solution →Heavy Light 2 White Falcon
White Falcon was amazed by what she can do with heavy-light decomposition on trees. As a resut, she wants to improve her expertise on heavy-light decomposition. Her teacher gave her an another assignment which requires path updates. As always, White Falcon needs your help with the assignment. You are given a tree with N nodes and each node's value Vi is initially 0. Let's denote the path fr
View Solution →Library Query
A giant library has just been inaugurated this week. It can be modeled as a sequence of N consecutive shelves with each shelf having some number of books. Now, being the geek that you are, you thought of the following two queries which can be performed on these shelves. Change the number of books in one of the shelves. Obtain the number of books on the shelf having the kth rank within the ra
View Solution →