{ }codelper
genericsinterfacesP0415

A board path that adds and caps

A board game has n cells in a row, numbered 1, 2, …, n from the left.
Cell i has a rule made of three integers d, lo and hi, and always lo ≤ hi.
When a token with score s passes cell i, d is first added to s.
If the sum is less than lo the score becomes lo, if it is greater than hi the score becomes hi, and otherwise the score is the sum itself.
The first line gives n, and the i-th of the next n lines gives d, lo and hi of cell i separated by single spaces.
The next line gives the number of commands q, and each of the next q lines gives one command.
- go l r x: a token with score x passes cells l, l+1, …, r in order.
Print the score after it passes cell r.
- set i d lo hi: change the rule of cell i to d, lo, hi.
Nothing is printed.
- top l r: among cells l to r, print the number of the cell with the largest d and that cell's d, separated by one space.
If several cells have the largest d, choose the one with the smallest number.
go does not change any rule, and the token starts afresh for every go.
Print one line for every go and top, in the order the commands appear.
Write one generic class (a class template in C++) SegTree that takes the value type T and an interface Monoid<T> saying how two such values are joined, and solve both go and top with that class.
Grading looks only at the output.

Input
1 ≤ n ≤ 200000, 1 ≤ q ≤ 10000.
Every d, lo, hi and x is an integer from -1000000 to 1000000, and lo ≤ hi always holds for the cell rules and in set.
1 ≤ l ≤ r ≤ n, 1 ≤ i ≤ n.
At least one go or top is given
Output
One score per go and one line "number d" per top, in the order the commands appear
Example 1 · stdin
5
3 0 10
-4 -5 5
2 -100 1
5 0 5
-1 -2 2
8
go 1 5 0
go 2 4 -3
top 1 5
set 3 5 -1 3
top 1 5
go 1 3 9
go 3 3 -50
top 4 5
stdout
2
2
4 5
3 5
3
-1
4 5
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 4 languages

This problem accepts only TypeScript, Java, C# and C++, which have generics (a class template in C++).
Python and JavaScript do not write types, so one class holds anything from the start, and C and Craykon have no type parameters.
The key is that passing several cells in a row still reduces to one rule of the form "add d, then cap to [lo, hi]".
Passing cell a and then cell b is the rule d = a.d + b.d, lo = clamp(a.lo + b.d, b.lo, b.hi), hi = clamp(a.hi + b.d, b.lo, b.hi).
The rule for passing no cell at all (the identity) is d = 0, lo = -∞, hi = +∞.
The value for top is a (d, number) pair; joining keeps the larger d, or the smaller number when d is equal, and the identity has d = -∞.
Needing only an identity and a join is exactly what Monoid<T> says, and the same SegTree is used with T = rule and T = (d, number).
Because it is a segment tree, each command joins only O(log n) times.
A solution that walks through the cells one by one (and scans cell by cell for top) looks at about 1.6 billion cells in one of the largest cases, so even in C++ some cases go over the judge's 2-second limit.
How it is written differs by language.
In TS one object fills interface Monoid<T> and is passed as new SegTree<Rule>(rules, ruleMonoid).
In Java an anonymous class fills interface Monoid<T>, and since new T[n] is a compile error (generic array creation), the nodes are kept in an ArrayList<T>.
In C# a class fills interface IMonoid<T>, new T[n] works as is, and a rule is a readonly record struct.
In C++ template <typename Monoid> uses Monoid::T, Monoid::identity() and Monoid::combine(a, b); no interface is written down, and the names are checked when you instantiate it as SegTree<RuleMonoid>.
The sum of all d grows up to 2×10^11, so Java, C# and C++ hold it in long (long long).
Trap one: joining in a different order gives a different result.
If the bottom-up range query joins the nodes picked at the left end and the right end into one variable in the order they are picked, top (a maximum) is still right but go is wrong.
go 1 5 0 in the example gives 5 instead of 2.
Collect the left part with left = combine(left, node) and the right part with right = combine(node, right), and join them at the end with combine(left, right).
Trap two: if the join formula caps to b's [lo, hi] first and adds b.d afterwards, it reverses the rule's order (add, then cap).
go 1 5 0 in the example gives 6.
Trap three: TS can put -Infinity and Infinity into the identity as they are, but integers in Java, C# and C++ have no infinity.
If the ends are Long.MIN_VALUE and Long.MAX_VALUE, adding d overflows and wraps to the other end (Java and C# wrap by default; signed overflow in C++ is undefined behaviour).
go 2 4 -3 in the example gives 5 instead of 2.
The solutions use 10^18, which does not overflow when d is added.
Trap four: TS Number.MIN_VALUE is not the smallest number but the smallest number greater than 0 (5e-324).
Using it for -∞ makes go 3 3 -50 in the example give 3 instead of -1.
Trap five: choosing for top only with a.d > b.d ? a : b keeps the right cell when d is equal.
In the example, top 1 5 after set 3 5 -1 3 gives 4 5 instead of 3 5.

TypeScriptmain.ts · 105 lines
import { readFileSync } from "node:fs"; // 합치기의 약속: 아무것도 없는 값(identity)과, 왼쪽 a 다음에 오른쪽 b를 잇는 combineinterface Monoid<T> {  identity: T;  combine(a: T, b: T): T;} // 어떤 T든 Monoid<T>만 있으면 구간 [l, r)의 값을 합쳐 주는 구간 트리class SegTree<T> {  private size = 1;  private t: T[];  private m: Monoid<T>;   constructor(values: T[], m: Monoid<T>) {    this.m = m;    while (this.size < values.length) this.size *= 2;    this.t = new Array<T>(2 * this.size).fill(m.identity);    for (let i = 0; i < values.length; i++) this.t[this.size + i] = values[i];    for (let i = this.size - 1; i >= 1; i--) this.t[i] = m.combine(this.t[2 * i], this.t[2 * i + 1]);  }   set(i: number, v: T): void {    i += this.size;    this.t[i] = v;    for (i >>= 1; i >= 1; i >>= 1) this.t[i] = this.m.combine(this.t[2 * i], this.t[2 * i + 1]);  }   query(l: number, r: number): T {    // 왼쪽에서 모은 것과 오른쪽에서 모은 것을 따로 둔다: 차례가 중요한 합치기도 있다    let left = this.m.identity;    let right = this.m.identity;    for (l += this.size, r += this.size; l < r; l >>= 1, r >>= 1) {      if (l & 1) left = this.m.combine(left, this.t[l++]);      if (r & 1) right = this.m.combine(this.t[--r], right);    }    return this.m.combine(left, right);  }} // 칸 여러 개를 이어 지난 결과도 "d를 더하고 [lo, hi]로 맞춘다" 꼴이다interface Rule { d: number; lo: number; hi: number; }interface Best { d: number; cell: number; } const clamp = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v)); const ruleMonoid: Monoid<Rule> = {  identity: { d: 0, lo: -Infinity, hi: Infinity },  combine: (a, b) => ({ d: a.d + b.d, lo: clamp(a.lo + b.d, b.lo, b.hi), hi: clamp(a.hi + b.d, b.lo, b.hi) }),}; const bestMonoid: Monoid<Best> = {  identity: { d: -Infinity, cell: 0 },  combine: (a, b) => (a.d !== b.d ? (a.d > b.d ? a : b) : (a.cell < b.cell ? a : b)),}; // 입력이 수십만 개라 글자 코드를 직접 읽는다(문자열을 통째로 나누는 것보다 빠르다)const src: string = readFileSync(0, "utf8");let p = 0;const skipSpace = (): void => { while (p < src.length && src.charCodeAt(p) <= 32) p++; };const next = (): string => {  skipSpace();  const start = p;  while (p < src.length && src.charCodeAt(p) > 32) p++;  return src.slice(start, p);};const num = (): number => {  skipSpace();  let sign = 1;  if (src.charCodeAt(p) === 45) { sign = -1; p++; } // '-'  let v = 0;  while (p < src.length && src.charCodeAt(p) > 32) v = v * 10 + (src.charCodeAt(p++) - 48);  return sign * v;}; const n = num();const rules: Rule[] = [];const bests: Best[] = [];for (let i = 1; i <= n; i++) {  const d = num(), lo = num(), hi = num();  rules.push({ d, lo, hi });  bests.push({ d, cell: i });}const ruleTree = new SegTree<Rule>(rules, ruleMonoid);const bestTree = new SegTree<Best>(bests, bestMonoid); const q = num();const out: string[] = [];for (let k = 0; k < q; k++) {  const cmd = next();  if (cmd === "go") {    const l = num(), r = num(), x = num();    const f = ruleTree.query(l - 1, r);    out.push(String(clamp(x + f.d, f.lo, f.hi)));  } else if (cmd === "set") {    const i = num(), d = num(), lo = num(), hi = num();    ruleTree.set(i - 1, { d, lo, hi });    bestTree.set(i - 1, { d, cell: i });  } else {    const l = num(), r = num();    const b = bestTree.query(l - 1, r);    out.push(`${b.cell} ${b.d}`);  }}console.log(out.join("\n"));
JavaMain.java · 110 lines
import java.io.*;import java.util.*; // 합치기의 약속: 아무것도 없는 값(identity)과, 왼쪽 a 다음에 오른쪽 b를 잇는 combineinterface Monoid<T> {    T identity();    T combine(T a, T b);} // 어떤 T든 Monoid<T>만 있으면 구간 [l, r)의 값을 합쳐 주는 구간 트리class SegTree<T> {    private final int size;    private final List<T> t;    private final Monoid<T> m;     SegTree(List<T> values, Monoid<T> m) {        this.m = m;        int s = 1;        while (s < values.size()) s *= 2;        size = s;        t = new ArrayList<>(Collections.nCopies(2 * size, m.identity())); // Java는 T[]를 new로 만들 수 없다        for (int i = 0; i < values.size(); i++) t.set(size + i, values.get(i));        for (int i = size - 1; i >= 1; i--) t.set(i, m.combine(t.get(2 * i), t.get(2 * i + 1)));    }     void set(int i, T v) {        i += size;        t.set(i, v);        for (i >>= 1; i >= 1; i >>= 1) t.set(i, m.combine(t.get(2 * i), t.get(2 * i + 1)));    }     T query(int l, int r) {        // 왼쪽에서 모은 것과 오른쪽에서 모은 것을 따로 둔다: 차례가 중요한 합치기도 있다        T left = m.identity(), right = m.identity();        for (l += size, r += size; l < r; l >>= 1, r >>= 1) {            if ((l & 1) == 1) left = m.combine(left, t.get(l++));            if ((r & 1) == 1) right = m.combine(t.get(--r), right);        }        return m.combine(left, right);    }} // 칸 여러 개를 이어 지난 결과도 "d를 더하고 [lo, hi]로 맞춘다" 꼴이다record Rule(long d, long lo, long hi) {}record Best(long d, int cell) {} public class Main {    static final long INF = 1_000_000_000_000_000_000L; // 10^18: 여기에 d를 더해도 long을 넘지 않는다     static long clamp(long v, long lo, long hi) { return Math.min(hi, Math.max(lo, v)); }     static final Monoid<Rule> RULES = new Monoid<>() {        public Rule identity() { return new Rule(0, -INF, INF); }        public Rule combine(Rule a, Rule b) {            return new Rule(a.d() + b.d(), clamp(a.lo() + b.d(), b.lo(), b.hi()), clamp(a.hi() + b.d(), b.lo(), b.hi()));        }    };     static final Monoid<Best> BESTS = new Monoid<>() {        public Best identity() { return new Best(-INF, 0); }        public Best combine(Best a, Best b) {            if (a.d() != b.d()) return a.d() > b.d() ? a : b;            return a.cell() < b.cell() ? a : b;        }    };     public static void main(String[] args) throws IOException {        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));        in.resetSyntax();        in.wordChars(33, 126);        in.whitespaceChars(0, 32);        int n = Integer.parseInt(word(in));        List<Rule> rules = new ArrayList<>();        List<Best> bests = new ArrayList<>();        for (int i = 1; i <= n; i++) {            long d = Long.parseLong(word(in)), lo = Long.parseLong(word(in)), hi = Long.parseLong(word(in));            rules.add(new Rule(d, lo, hi));            bests.add(new Best(d, i));        }        SegTree<Rule> ruleTree = new SegTree<>(rules, RULES);        SegTree<Best> bestTree = new SegTree<>(bests, BESTS);         int q = Integer.parseInt(word(in));        StringBuilder out = new StringBuilder();        for (int k = 0; k < q; k++) {            String cmd = word(in);            if (cmd.equals("go")) {                int l = Integer.parseInt(word(in)), r = Integer.parseInt(word(in));                long x = Long.parseLong(word(in));                Rule f = ruleTree.query(l - 1, r);                out.append(clamp(x + f.d(), f.lo(), f.hi())).append('\n');            } else if (cmd.equals("set")) {                int i = Integer.parseInt(word(in));                long d = Long.parseLong(word(in)), lo = Long.parseLong(word(in)), hi = Long.parseLong(word(in));                ruleTree.set(i - 1, new Rule(d, lo, hi));                bestTree.set(i - 1, new Best(d, i));            } else {                int l = Integer.parseInt(word(in)), r = Integer.parseInt(word(in));                Best b = bestTree.query(l - 1, r);                out.append(b.cell()).append(' ').append(b.d()).append('\n');            }        }        System.out.print(out);    }     static String word(StreamTokenizer in) throws IOException {        in.nextToken();        return in.sval;    }}
C#Main.cs · 114 lines
using System;using System.IO;using System.Text; // 합치기의 약속: 아무것도 없는 값(Identity)과, 왼쪽 a 다음에 오른쪽 b를 잇는 Combineinterface IMonoid<T>{    T Identity { get; }    T Combine(T a, T b);} // 어떤 T든 IMonoid<T>만 있으면 구간 [l, r)의 값을 합쳐 주는 구간 트리class SegTree<T>{    private readonly int size = 1;    private readonly T[] t;    private readonly IMonoid<T> m;     public SegTree(T[] values, IMonoid<T> m)    {        this.m = m;        while (size < values.Length) size *= 2;        t = new T[2 * size];        Array.Fill(t, m.Identity);        Array.Copy(values, 0, t, size, values.Length);        for (int i = size - 1; i >= 1; i--) t[i] = m.Combine(t[2 * i], t[2 * i + 1]);    }     public void Set(int i, T v)    {        i += size;        t[i] = v;        for (i >>= 1; i >= 1; i >>= 1) t[i] = m.Combine(t[2 * i], t[2 * i + 1]);    }     public T Query(int l, int r)    {        // 왼쪽에서 모은 것과 오른쪽에서 모은 것을 따로 둔다: 차례가 중요한 합치기도 있다        T left = m.Identity, right = m.Identity;        for (l += size, r += size; l < r; l >>= 1, r >>= 1)        {            if ((l & 1) == 1) left = m.Combine(left, t[l++]);            if ((r & 1) == 1) right = m.Combine(t[--r], right);        }        return m.Combine(left, right);    }} // 칸 여러 개를 이어 지난 결과도 "d를 더하고 [lo, hi]로 맞춘다" 꼴이다readonly record struct Rule(long D, long Lo, long Hi);readonly record struct Best(long D, int Cell); class RuleMonoid : IMonoid<Rule>{    public const long Inf = 1_000_000_000_000_000_000L; // 10^18: 여기에 D를 더해도 long을 넘지 않는다    public Rule Identity => new(0, -Inf, Inf);    public Rule Combine(Rule a, Rule b) =>        new(a.D + b.D, Math.Clamp(a.Lo + b.D, b.Lo, b.Hi), Math.Clamp(a.Hi + b.D, b.Lo, b.Hi));} class BestMonoid : IMonoid<Best>{    public Best Identity => new(-RuleMonoid.Inf, 0);    public Best Combine(Best a, Best b) =>        a.D != b.D ? (a.D > b.D ? a : b) : (a.Cell < b.Cell ? a : b);} class Program{    static void Main()    {        string[] w = Console.In.ReadToEnd().Split((char[])null, StringSplitOptions.RemoveEmptyEntries);        int p = 0;        int n = int.Parse(w[p++]);        var rules = new Rule[n];        var bests = new Best[n];        for (int i = 0; i < n; i++)        {            long d = long.Parse(w[p++]), lo = long.Parse(w[p++]), hi = long.Parse(w[p++]);            rules[i] = new Rule(d, lo, hi);            bests[i] = new Best(d, i + 1);        }        var ruleTree = new SegTree<Rule>(rules, new RuleMonoid());        var bestTree = new SegTree<Best>(bests, new BestMonoid());         int q = int.Parse(w[p++]);        var sb = new StringBuilder();        for (int k = 0; k < q; k++)        {            string cmd = w[p++];            if (cmd == "go")            {                int l = int.Parse(w[p++]), r = int.Parse(w[p++]);                long x = long.Parse(w[p++]);                Rule f = ruleTree.Query(l - 1, r);                sb.Append(Math.Clamp(x + f.D, f.Lo, f.Hi)).Append('\n');            }            else if (cmd == "set")            {                int i = int.Parse(w[p++]);                long d = long.Parse(w[p++]), lo = long.Parse(w[p++]), hi = long.Parse(w[p++]);                ruleTree.Set(i - 1, new Rule(d, lo, hi));                bestTree.Set(i - 1, new Best(d, i));            }            else            {                int l = int.Parse(w[p++]), r = int.Parse(w[p++]);                Best b = bestTree.Query(l - 1, r);                sb.Append(b.Cell).Append(' ').Append(b.D).Append('\n');            }        }        Console.Out.Write(sb);    }}
C++main.cpp · 100 lines
#include <algorithm>#include <cstdio>#include <string>#include <vector>using namespace std; // 어떤 T든, 아무것도 없는 값 identity와 "왼쪽 a 다음에 오른쪽 b"를 잇는 combine만 있으면// 구간 [l, r)의 값을 합쳐 주는 구간 트리. Monoid는 T, identity(), combine(a, b)를 가진 타입이다template <typename Monoid>class SegTree {    using T = typename Monoid::T;    int size = 1;    vector<T> t; public:    explicit SegTree(const vector<T>& values) {        while (size < (int)values.size()) size *= 2;        t.assign(2 * size, Monoid::identity());        copy(values.begin(), values.end(), t.begin() + size);        for (int i = size - 1; i >= 1; i--) t[i] = Monoid::combine(t[2 * i], t[2 * i + 1]);    }     void set(int i, const T& v) {        i += size;        t[i] = v;        for (i >>= 1; i >= 1; i >>= 1) t[i] = Monoid::combine(t[2 * i], t[2 * i + 1]);    }     T query(int l, int r) const {        // 왼쪽에서 모은 것과 오른쪽에서 모은 것을 따로 둔다: 차례가 중요한 합치기도 있다        T left = Monoid::identity(), right = Monoid::identity();        for (l += size, r += size; l < r; l >>= 1, r >>= 1) {            if (l & 1) left = Monoid::combine(left, t[l++]);            if (r & 1) right = Monoid::combine(t[--r], right);        }        return Monoid::combine(left, right);    }}; const long long INF = 1'000'000'000'000'000'000LL; // 10^18: 여기에 d를 더해도 long long을 넘지 않는다 // 칸 여러 개를 이어 지난 결과도 "d를 더하고 [lo, hi]로 맞춘다" 꼴이다struct Rule { long long d, lo, hi; };struct Best { long long d; int cell; }; struct RuleMonoid {    using T = Rule;    static Rule identity() { return {0, -INF, INF}; }    static Rule combine(const Rule& a, const Rule& b) {        return {a.d + b.d, clamp(a.lo + b.d, b.lo, b.hi), clamp(a.hi + b.d, b.lo, b.hi)};    }}; struct BestMonoid {    using T = Best;    static Best identity() { return {-INF, 0}; }    static Best combine(const Best& a, const Best& b) {        if (a.d != b.d) return a.d > b.d ? a : b;        return a.cell < b.cell ? a : b;    }}; int main() {    // 입력이 수십만 개라 scanf로 읽는다(macOS의 libc++ cin은 이 크기에서 몇 초 걸린다)    int n;    scanf("%d", &n);    vector<Rule> rules(n);    vector<Best> bests(n);    for (int i = 0; i < n; i++) {        scanf("%lld %lld %lld", &rules[i].d, &rules[i].lo, &rules[i].hi);        bests[i] = {rules[i].d, i + 1};    }    SegTree<RuleMonoid> ruleTree(rules);    SegTree<BestMonoid> bestTree(bests);     int q;    scanf("%d", &q);    char cmd[8];    for (int k = 0; k < q; k++) {        scanf("%7s", cmd);        if (string(cmd) == "go") {            int l, r;            long long x;            scanf("%d %d %lld", &l, &r, &x);            Rule f = ruleTree.query(l - 1, r);            printf("%lld\n", clamp(x + f.d, f.lo, f.hi));        } else if (string(cmd) == "set") {            int i;            long long d, lo, hi;            scanf("%d %lld %lld %lld", &i, &d, &lo, &hi);            ruleTree.set(i - 1, {d, lo, hi});            bestTree.set(i - 1, {d, i});        } else {            int l, r;            scanf("%d %d", &l, &r);            Best b = bestTree.query(l - 1, r);            printf("%d %lld\n", b.cell, b.d);        }    }}