Problem solution · C++

Queue Operate All Composite

Queue Operate All Composite: a C++ solution using stack-based processing. Learn the idea, check the complexity, and read the full code, with credit to NyaanNyaan Competitive Programming Library.

Technique
Stack-based processing
Source
NyaanNyaan Competitive Programming Library
Length
33 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Stack-based processing

For Queue Operate All Composite, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.

  1. Define what every stack entry represents.
  2. Pop entries once the current item resolves or invalidates them.
  3. Push the current item with only the information later steps need.

Code notes

  • 33 lines of C++ from the credited upstream file yosupo-swag.test.cpp.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

If each item is pushed and popped at most once, the stack work is linear.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from NyaanNyaan Competitive Programming Library by NyaanNyaan and is used under the CC0-1.0 licence.

Full codeQueue Operate All Composite · C++C++
Use this to learn the idea, then write your own version.
#define PROBLEM "https://judge.yosupo.jp/problem/queue_operate_all_composite" #include "../../template/template.hpp"#include "../../data-structure/slide-window-aggregation.hpp"#include "../../misc/fastio.hpp"#include "../../modint/montgomery-modint.hpp" using namespace Nyaan; void Nyaan::solve() {  using mint = LazyMontgomeryModInt<998244353>;  using p = pair<mint, mint>;  auto f = [](const p &a, const p &b) {    return p{a.first * b.first, a.second * b.first + b.second};  };  SlideWindowAggregation<p, decltype(f)> swag(f, p{1, 0});  int Q;  rd(Q);  rep(_, Q) {    int cmd;    rd(cmd);    if (cmd == 0) {      int a, b;      rd(a, b);      swag.push(p{a, b});    } else if (cmd == 1) {      swag.pop();    } else {      int x;      rd(x);      p q = swag.query();      wtn((q.first * x + q.second).get());    }  }}

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗