B. Processing Queries
time limit per test
memory limit per test
input
output
n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti
When a query appears server may react in three possible ways:
- If server is free and query queue is empty, then server immediately starts to process this query.
- b
- b
x, and the server finishes to process another query at exactly the same moment, we consider that first query is picked from the queue and only then new query appears.
-1
Input
n and b (1 ≤ n, b ≤ 200 000) — the number of queries and the maximum possible size of the query queue.
n lines with queries descriptions (in chronological order). Each description consists of two integers ti and di(1 ≤ ti, di ≤ 109), where ti is the moment of time when the i-th query appears and di is the time server needs to process it. It is guaranteed that ti - 1 < ti for all i > 1.
Output
n integers e1, e2, ..., en, where ei is the moment the server will finish to process the i-th query (queries are numbered in the order they appear in the input) or - 1
Examples
input
5 1 2 9 4 8 10 9 15 2 19 1
output
11 19 -1 21 22
input
4 1 2 8 4 8 10 9 15 2
output
10 18 27 -1
定义一个队列,队中最多可以放n+1个Queries.其中队列中的第一个查询的状态是正在处理。每次遇到一个新的查询t1, d1, 从队列首取出请求观察其结束时间是否小于等于t1若是,则删除队首元素,在取队首元素比较,以此类推,最后观察队列中元素是否小于n+1,若是则插入新的请求
#include <bits/stdc++.h>
#define maxn 200005
#define MOD 1000000007
using namespace std;
typedef long long ll;
struct Node{
Node(){
}
Node(int a, int b){
i = a;
d = b;
}
int i, d;
};
queue<Node> q;
ll ans[maxn];
int main(){
//freopen("in.txt", "r", stdin);
int n, b, t, d;
ll tt = 0;
scanf("%d%d", &n, &b);
for(int i = 0; i < n; i++){
scanf("%d%d", &t, &d);
if(i == 0){
tt = t;
q.push(Node(i, d));
continue;
}
while(!q.empty() && t >= q.front().d + tt){
tt += q.front().d;
ans[q.front().i] = tt;
q.pop();
}
if(q.size() < b+1){
if(q.empty())
tt = t;
q.push(Node(i, d));
}
else
ans[i] = -1;
}
while(!q.empty()){
tt += q.front().d;
ans[q.front().i] = tt;
q.pop();
}
printf("%I64d", ans[0]);
for(int i = 1; i < n; i++)
printf(" %I64d", ans[i]);
puts("");
return 0;
}