双端队列(deque)
题目描述:
给定Q次操作,每次操作有如下两种选择
1 x c: Insert c balls, with a number x written on each of them, to the right end of the cylinder.
2 c: Take out the c leftmost balls contained in the cylinder and print the sum of the numbers written on the balls that have been taken out.
数据范围:
1 ≤ Q ≤ 2×105
0 ≤ x ≤ 109
0 ≤ c ≤ 109
解题思路:
由于x, c的范围过大,使用一维队列时,样例二会re, 因此该题可以考虑使用二维,直接记录数字和个数
使用双端队列可以方便的对队头元素进行删除和插入
val记录小球上的数字, cnt记录该段同种数字的小球的个数
当 c < cnt 时,注意要及时更新当前队头小球的数量
key code:
void solve()
{
LL n;
cin >> n;
deque<pair<LL,LL> >dq;
while(n --)
{
LL m;
cin >> m;
if(m == 1)
{
LL a, b;
cin >> a >> b;
dq.push_back({a, b});
}
else
{
LL c, sum = 0;
cin >> c;
while(c)
{
auto it = dq.front();
dq.pop_front();
LL val = it.first, cnt = it.second;
if(c < cnt)
{
cnt -= c;
sum += c * val;
c = 0;
dq.push_front({val, cnt});
}
else
{
c -= cnt;
sum += val * cnt;
}
}
cout << sum << endl;
}
}
}

浙公网安备 33010602011771号