Lexicographically Smallest Path

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

Bessie is given an undirected graph with $N$ ($1\le N\le 2\cdot 10^5$) vertices labeled $1\dots N$ and $M$ edges ($N - 1\le M\le 2\cdot 10^5$). Each edge is described by two integers $u, v$ ($1\le u, v\le N$) describing an undirected edge between nodes $u$ and $v$ and a lowercase Latin letter $c$ in the range a..z that is the value on the edge. The graph given is guaranteed to be connected. There may be multiple edges or self-loops.

Define $f(a, b)$ as the lexicographically smallest concatenation of edge values over all paths starting from node $a$ and ending at node $b$. A path may contain the same edge more than once (i.e., cycles are allowed).

For each $i$ ($1\le i\le N$), help Bessie determine the length of $f(1, i)$. Output this length if it is finite, otherwise output $-1$.

## Input Format

The first line contains $T$ ($1\le T\le 10$), the number of independent tests. Each test is specified in the following format:

The first line contains $N$ and $M$.

The next $M$ lines each contain two integers followed by a lowercase Latin character.

It is guaranteed that neither the sum of $N$ nor the sum of $M$ over all tests exceeds $4\cdot 10^5$.

## Output Format

For each test, output $N$ space-separated integers on a new line.

## Examples

**Input 1**

```
2
1 0
2 2
1 1 a
2 1 b
```

**Output 1**

```
0
0 -1
```

**Input 2**

```
2
7 7
1 2 a
1 3 a
2 4 b
3 5 a
5 6 a
6 7 a
7 4 a
4 3
1 2 z
2 3 x
3 4 y
```

**Output 2**

```
0 1 1 5 2 3 4
0 1 2 -1
```

## Note

For the first test case of the first example, node $1$ can be reached with an empty path, so the answer is $0$. In the second test case, node $2$ cannot have a lexicographically smallest path, since FJ can repeat the `'a'` self-loop any number of times before moving to node $2$, producing arbitrarily long strings that are still lexicographically minimal. Therefore, the answer for node $2$ is $-1$.

For the first test case of the second example, node $1$ has distance $0$. Nodes $2$ and $3$ are adjacent with node $1$, and they have distance $1$. For nodes $4, 5, 6$, and $7$, it can be proven that the lexicographically shortest path does not pass through the edge between node $2$ and $4$.

For the second test case of the second example, node $4$ again has no lexicographically smallest path, since the string can be extended indefinitely while remaining lexicographically minimal. Thus, its answer is $-1$.

## Scoring

- Inputs 3-4: Every character is `a`
- Inputs 5-8: Every character is `a` or `b`
- Inputs 9-14: $N, M\le 5000$
- Inputs 15-22: No additional constraints

**Problem credits:** Daniel Zhu and Yash Belani

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 10, "T"); inf.readEoln();
    long long sumN = 0, sumM = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(1, 400000, "N"); inf.readSpace();
        int M = inf.readInt(std::max(0, N - 1), 400000, "M"); inf.readEoln();
        sumN += N; sumM += M;
        for (int e = 1; e <= M; e++) {
            inf.readInt(1, N, "u"); inf.readSpace();
            inf.readInt(1, N, "v"); inf.readSpace();
            char c = inf.readChar();
            ensuref(c >= 'a' && c <= 'z', "test %d edge %d: value must be a-z, got '%c'", tc, e, c);
            inf.readEoln();
        }
    }
    ensuref(sumN <= 400000, "sum N is %lld > 4e5", sumN);
    ensuref(sumM <= 400000, "sum M is %lld > 4e5", sumM);
    inf.readEof();
    return 0;
}

#include "bits/stdc++.h"
#define endl '\n'
#define f first
#define s second
using namespace std;

const int N = 2e5 + 5, A = 28;
int n, m;
vector<pair<int, int>> g[N];
int ans[N];

void ac() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) ans[i] = -1, g[i].clear();
    for (int i = 1; i <= m; i++) {
        int a, b;
        char x;
        cin >> a >> b >> x;
        int c = (x - 'a');  // converting characters to integers
        g[a].push_back({c, b});
        g[b].push_back({c, a});
    }
    ans[1] = 0;
    vector<int> active;
    active.push_back(1);
    while (active.size()) {
        int min_edge = A;
        for (int i : active) {  // finding min edge to take
            for (auto j : g[i]) min_edge = min(min_edge, j.f);
        }
        vector<int> next_active;
        for (int i : active) {
            for (auto j : g[i]) {
                if (ans[j.s] == -1 && j.f == min_edge) {  // extending string
                    ans[j.s] = ans[i] + 1;
                    next_active.push_back(j.s);
                }
            }
        }
        swap(next_active, active);
    }
    for (int i = 1; i <= n; i++) {
        if (i > 1) cout << " ";
        cout << ans[i];
    }
    cout << "\n";
}

int main() {
    int t;
    cin >> t;
    while (t--) ac();
}

verbatim earliest root score=100 submission #70940


The Chase

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

Bessie is trying to evade the farmers. The farmers own $N$ ($2\le N\le 5\cdot 10^5$) farms with a one-way road between the $i$-th farm and the $a_i$-th farm ($1\le i\le N$, $a_i\ne i$). There are $F$ ($1\le F\le N$) farmers and the $i$-th farmer is initially stationed at farm $s_i$ ($1\le s_i\le N$, all $s_i$ unique). At each time step, every farmer takes the road at their current farm and moves to the next. Bessie gets caught if she is ever located at the same farm as any farmer.

Suppose Bessie starts at some farm $b$. At each time step, she has two options: she can either choose to rest (stay at her current farm) or take the road and move to the next farm. If she chooses to move, she moves simultaneously with the farmers. Bessie moves so that she is never caught by any farmer in a finite number of timesteps.

For each starting farm $b$ ($1\le b\le N$), find the maximum number of times Bessie can choose the rest option if she starts at farm $b$.

## Input Format

The first line contains $N$ and $F$, the number of farms and the number of farmers.

The second line contains $a_1\ldots a_N$, the one-way roads going out of each farm.

The third line contains $s_1\ldots s_F$, the starting locations of each farmer.

## Output Format

Output $N$ lines, the $b$-th of which must consist of a single integer denoting the maximum number of times Bessie can choose the rest option if she starts at farm $b$. If there is no way for Bessie to ensure she is never caught after a finite number of timesteps, then output $-1$. If Bessie can rest an infinite number of times, then output $-2$.

## Examples

**Input 1**

```
4 1
2 1 4 3
1
```

**Output 1**

```
-1
0
-2
-2
```

## Note

- Farm 1: If Bessie starts at a farm with a farmer, then she is caught immediately, and you should output $-1$.
- Farm 2: Bessie must choose to move at every timestep to avoid being caught by the farmer who starts at farm $1$.
- Farms 3-4: Bessie can rest an infinite number of times without being caught.

## Scoring

- Input 2: $N\le 50$
- Inputs 3-10: $N\le 2000$
- Inputs 11-20: No additional constraints

**Problem credits:** Alex Liang

#include "testlib.h"
#include <set>
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int N = inf.readInt(2, 500000, "N"); inf.readSpace();
    int F = inf.readInt(1, N, "F"); inf.readEoln();
    for (int i = 1; i <= N; i++) {
        inf.readInt(1, N, "a_i");
        if (i < N) inf.readSpace();
    }
    inf.readEoln();
    std::set<int> seen;
    for (int i = 1; i <= F; i++) {
        int s = inf.readInt(1, N, "s_i");
        ensuref(seen.insert(s).second, "farmer start %d duplicated", s);
        if (i < F) inf.readSpace();
    }
    inf.readEoln();
    inf.readEof();
    return 0;
}

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(0); cin.tie(0);
    int n, f;
    cin >> n >> f;

    vector<int> nxt(n + 1), hasFarmer(n + 1, 0);
    vector<vector<int>> radj(n + 1);

    for (int i = 1; i <= n; i++) {
        cin >> nxt[i];
        radj[nxt[i]].push_back(i);
    }
    for (int i = 1; i <= f; i++) {
        int s;
        cin >> s;
        hasFarmer[s] = 1;
    }

    vector<int> vis(n + 1, 0), close(n + 1, (int)1e9), ans(n + 1);

    for (int start = 1; start <= n; start++) {
        if (vis[start])
            continue;

        // Get cycle
        int cur = start;
        vector<int> cycle;

        while (vis[cur] != 2) {
            if (++vis[cur] == 2)
                cycle.push_back(cur);
            cur = nxt[cur];
        }

        // Get tree info
        int csz = cycle.size();
        vector<int> good(csz, 1), chop(csz, 1e9);
        vector<pair<int, int>> relevant;

        for (int i = 0; i < csz; i++) {
            function<void(int, int)> dfs = [&](int cur, int d){
                int pos = (i - d % csz + csz) % csz;
                vis[cur] = 1;
                relevant.push_back({cur, pos});

                if (hasFarmer[cur]) {
                    good[pos] = 0;
                    close[cur] = 0;
                }
                for (int to : radj[cur]) {
                    if (cur == cycle[i] && to == cycle[(i - 1 + csz) % csz])
                        continue;
                    dfs(to, d + 1);
                    close[cur] = min(close[cur], close[to] + 1);
                }
            };
            dfs(cycle[i], 0);
        }
        // Get distances to nearest good waiting spot
        for (int i = 2 * csz - 1; i >= 0; i--)
            chop[i % csz] = good[i % csz] ? 0 : chop[(i + 1) % csz] + 1;

        // Adjust close for cycle nodes
        for (int i = 0; i < 2 * csz - 1; i++)
            close[cycle[i % csz]] = min(close[cycle[i % csz]], close[cycle[(i - 1 + csz) % csz]] + 1);

        // Solve for each node
        for (auto [cur, st] : relevant) {
            if (close[cur] >= (int)1e8) {
                ans[cur] = -2;
                continue;
            }

            int ret = close[cur] - 1 - chop[(st - close[cur] % csz + 1 + csz) % csz];
            ans[cur] = ret >= 0 ? ret : -1;
        }
    }
    for (int i = 1; i <= n; i++)
        cout << ans[i] << "\n";
}

verbatim earliest root score=100 submission #70941


Circle of Cows

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

Farmer John has $N$ ($2\le N\le 1000$) cows at distinct locations $l_1, \dots, l_N$ along a circle of circumference $C$ ($0\le l_1 < l_2 < \dots < l_N < C$, $N\le C\le 10^9$).

FJ will select $k$ pairs of cows, where $1\le k\le \lfloor N/2\rfloor$, and no cow is selected more than once. He wants to select the pairs such that the minimum distance between any two cows in the same pair along the circumference of the circle is maximized.

For each value of $k$, help FJ determine the maximum possible minimum distance.

## Input Format

The first line contains $N$ and $C$.

The second line contains $l_1 \dots l_N$.

## Output Format

Output a single line with $\lfloor N/2\rfloor$ space-separated integers, with the answers for $k = 1\dots \lfloor N/2\rfloor$ in that order.

## Examples

**Input 1**

```
4 100
0 25 50 75
```

**Output 1**

```
50 50
```

**Input 2**

```
4 100
0 1 2 99
```

**Output 2**

```
3 2
```

## Note

For the first example:

- For $k = 1$, cow $1$ can be paired to cow $3$, which is distance $50$ away along the circumference of the circle, making the answer $50$.
- For $k = 2$, cow $1$ can be paired to cow $3$, and cow $2$ can be paired to cow $4$, which is distance $50$ away from it along the circumference of the circle, making the answer still $50$.

For the second example:

- For $k = 1$, cow $3$ can be paired to cow $4$, which is distance $2 + 100 - 99 = 3$ away from it along the circumference of the circle, making the answer $3$.
- For $k = 2$, cow $1$ can be paired to cow $3$ and cow $2$ can be paired to cow $4$. Each of these pairs contains two cows at a distance of $2$ from each other along the circumference of the circle, making the answer $2$.

## Scoring

- Inputs 3-4: $2 l_N\le C$
- Inputs 5-6: $N\le 20$
- Inputs 7-14: $N\le 100$
- Inputs 15-22: No additional constraints

**Problem credits:** Benjamin Qi

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int N = inf.readInt(2, 1000, "N");
    inf.readSpace();
    int C = inf.readInt(N, 1000000000, "C");
    inf.readEoln();
    long long prev = -1;
    for (int i = 1; i <= N; i++) {
        int l = inf.readInt(0, C - 1, "l_i");
        ensuref(l > prev, "l must be strictly increasing (index %d: %d <= %lld)", i, l, prev);
        prev = l;
        if (i < N) inf.readSpace();
    }
    inf.readEoln();
    inf.readEof();
    return 0;
}

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    int N, C;
    cin >> N >> C;
    vector<int> L(N);
    for (auto & x: L) {
        cin >> x;
    }

    vector<int> ans(N / 2 + 1);

    for (int i = 0; i < N; ++i) {
        for (int j = i + 1; j < N; ++j) {

            int i2 = (i + 1) % N, j2 = (j + 1) % N;
            int min_dist = min(L.at(j) - L.at(i), C - (L.at(j) - L.at(i)));
            int cnt = 1;

            while (i2 != j && j2 != i) {
                // distance from L[i2] to L[j2] in the positive direction
                int cur_dist = i2 < j2 ? L.at(j2) - L.at(i2) : C - (L.at(i2) - L.at(j2));
                if (cur_dist < min_dist) {
                    j2 = (j2 + 1 == N ? 0 : j2 + 1);
                } else if (C - cur_dist < min_dist) {
                    i2 = (i2 + 1 == N ? 0 : i2 + 1);
                } else {
                    cnt++;
                    i2 = (i2 + 1 == N ? 0 : i2 + 1);
                    j2 = (j2 + 1 == N ? 0 : j2 + 1);
                }
            }
            ans.at(cnt) = max(ans.at(cnt), min_dist);
        }
    }

    ans.erase(ans.begin());
    for (int i = (int)ans.size() - 2; i >= 0; --i) {
        ans.at(i) = max(ans.at(i), ans.at(i + 1));
    }
    for (int i = 0; i < N / 2; ++i) {
        cout << ans[i] << " \n"[i + 1 == N / 2];
    }
}

verbatim earliest root score=100 submission #70936


Cow Circle

**Time limit:** 6 seconds    **Memory limit:** 512 megabytes

> **Note:** The time limit for this problem is 6s, thrice the default. The memory limit for this problem is 512 MB, twice the default.

## Description

Farmer John has $N$ ($1\le N\le 5000$) cows standing around a circular track divided into $M$ ($1\le M\le 10^6$) equally spaced positions, numbered $0$ to $M - 1$ clockwise. Cow $i$ is initially at position $x_i$, where $0 = x_1 < x_2 < \dots < x_N < M$.

For each $1\le i\le N$, cow $i$ will independently and randomly choose either to face clockwise or counterclockwise with some probability specific to that cow. Once a cow has chosen her initial direction, she begins moving continuously in that direction at a constant speed of one position per minute. Whenever two cows meet (i.e., they occupy the same space), they bounce off of each other: immediately reversing their directions and continuing to move at the same speed in that direction.

Farmer John is wondering where cow $1$ will end up. For each $0\le i < M$, find the probability that cow $1$ is at position $i$ after $K$ ($1\le K\le 10^{18}$) minutes.

## Input Format

The first line contains $T$ ($1\le T\le 100$), the number of independent test cases. Each test case is specified as follows:

The first line of each test case contains $N$ ($1\le N\le 5000$), $M$ ($1\le M\le 10^6$), and $K$ ($1\le K\le 10^{18}$).

The second line contains $N$ integers $p_1, \dots, p_N$ ($0\le p_i < 10^9 + 7$) where if $\frac{a_i}{b_i}$ is the probability cow $i$ goes clockwise, then $p_i\cdot b_i\equiv a_i\pmod{10^9 + 7}$.

The third and final line contains $N$ integers $x_1, x_2, \dots, x_N$.

It is guaranteed that the sum of $N^2$ over all test cases is $\le 5000^2$ and the sum of $M$ over all test cases is $\le 10^6$.

## Output Format

Output a new line for each test case. The line for each test case should be formatted as follows:

For every $0\le i < M$, let $\frac{p_i}{q_i}$ be the probability cow $1$ is in position $i$ at the end of $K$ minutes. Output $M$ space-separated integers $p_i q_i^{-1}\pmod{10^9 + 7}$ (where $p_i q_i^{-1}\cdot q_i\equiv p_i\pmod{10^9 + 7}$).

## Examples

**Input 1**

```
3
2 2 1
500000004 500000004
0 1
3 3 1
500000004 500000004 500000004
0 1 2
5 10 13
500000004 1 500000004 0 500000004
0 3 4 7 9
```

**Output 1**

```
500000004 500000004
500000004 250000002 250000002
0 0 0 125000001 375000003 0 125000001 375000003 0 0
```

## Note

For the first test case, both cows have a $\frac{1}{2}$ chance of going in either direction. If both pick the same direction, they will end up swapping positions (so cow $1$ ends up at $1$). Otherwise, they will bounce off in the middle and return to their original positions. Therefore, there is a $\frac{1}{2}$ chance for cow $1$ to end up at $0$ and a $\frac{1}{2}$ chance for cow $1$ to end up at $1$.

For the second test case, all cows again have a $\frac{1}{2}$ chance of going in either direction. For each combination of directions, here is where cow $1$ ends up at:

- CW, CW, CW: $1$
- CW, CW, CCW: $1$
- CCW, CCW, CCW: $2$
- CCW, CW, CCW: $2$
- CW, CCW, CW: $0$
- CW, CCW, CCW: $0$
- CCW, CW, CW: $0$
- CCW, CCW, CW: $0$

## Scoring

- Input 2: $K\le 100$, $N\le 10$
- Input 3: $N\le 10$
- Inputs 4-7: $\sum N^3\le 500^3$
- Inputs 8-11: $K < \frac{M}{2}$
- Inputs 12-15: No additional constraints

**Problem credits:** Sujay Konda

#include "testlib.h"
const long long MOD = 1000000007LL;
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 100, "T");
    inf.readEoln();
    long long sumN2 = 0, sumM = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(1, 5000, "N"); inf.readSpace();
        int M = inf.readInt(1, 1000000, "M"); inf.readSpace();
        inf.readLong(1, 1000000000000000000LL, "K");
        inf.readEoln();
        sumN2 += (long long)N * N; sumM += M;
        for (int i = 1; i <= N; i++) {
            inf.readInt(0, (int)(MOD - 1), "p_i");
            if (i < N) inf.readSpace();
        }
        inf.readEoln();
        long long prev = -1;
        for (int i = 1; i <= N; i++) {
            int x = inf.readInt(0, M - 1, "x_i");
            if (i == 1) ensuref(x == 0, "test %d: x_1 must be 0, got %d", tc, x);
            ensuref(x > prev, "test %d: x must be strictly increasing (idx %d: %d <= %lld)", tc, i, x, prev);
            prev = x;
            if (i < N) inf.readSpace();
        }
        inf.readEoln();
    }
    ensuref(sumN2 <= 25000000LL, "sum N^2 is %lld > 5000^2", sumN2);
    ensuref(sumM <= 1000000LL, "sum M is %lld > 1e6", sumM);
    inf.readEof();
    return 0;
}

#include <bits/stdc++.h>
using namespace std;

using ll = long long;

const int MOD = 1e9 + 7;

int bpow(int x, int y) {
    return (y == 0) ? 1 : ((ll)bpow((ll)x * x % MOD, y / 2) * ((y % 2) ? x : 1) % MOD);
}

void mulp(vector<int>& poly, int pr) {
    int npr = (MOD + 1 - pr) % MOD;
    if(npr == 0) return;
    poly.push_back(0);
    for(int i = poly.size() - 2; i >= 0; i--) {
        poly[i + 1] = (poly[i + 1] + (ll)npr * poly[i]) % MOD;
        poly[i] = ((ll)pr * poly[i]) % MOD;
    }
}
void divp(vector<int>& poly, int pr, int ipr) {
    int npr = (MOD + 1 - pr) % MOD;
    if(npr == 0) return;
    int v = poly.back();
    for(int i = poly.size() - 1; i >= 1; i--) {
        int nv = poly[i - 1];
        poly[i - 1] = (ll)v * ipr % MOD;
        v = (nv - (ll)poly[i - 1] * pr) % MOD;
        if(v < 0) v += MOD;
    }
    assert(v == 0);
    poly.pop_back();
}

void tc() {
    int N, M; cin >> N >> M;
    ll K; cin >> K;

    ll L = ((2 * K) / M) % N;
    ll E = (2 * K) % M;

    vector<int> p(N), x(N);
    for(int i = 0; i < N; i++) cin >> p[i];
    for(int i = 0; i < N; i++) cin >> x[i];

    auto get = [&] (int i) {
        if(i >= N) return x[i - N] + M;
        else return x[i];
    };

    auto solveR = [&] () {
        vector<int> ip(N);
        for(int i = 0; i < N; i++) ip[i] = bpow(MOD + 1 - p[i], MOD - 2);

        int j = 0;
        vector<int> ans(M);
        vector<int> cpoly(1, 1), opoly(1, 1);
        for(int i = 0; i < N; i++) {
            mulp(opoly, p[i]);
        }
        for(int i = 0; i < N; i++) {
            if(i > 0)
                mulp(opoly, p[i - 1]);
            while(get(j) - get(i) <= E) {
                mulp(cpoly, p[j % N]);
                divp(opoly, p[j % N], ip[j % N]);
                j++;
            }
            divp(cpoly, p[i], ip[i]);

            int cans = 0;
            int clc = (N - i) % N;
            for(int lc = 0; lc < N; lc++) {
                int olc = lc - clc;
                if(clc < cpoly.size() && olc >= 0 && olc < opoly.size()) {
                    cans = (cans + (ll)cpoly[clc] * opoly[olc]) % MOD;
                }
                clc -= L;
                if(clc < 0) clc += N;
            }
            int endp = ((x[i] + K) % M + M) % M;
            ans[endp] = (ans[endp] + (ll)p[i] * cans) % MOD;
        }
        return ans;
    };

    vector<int> ans = solveR();

    for(int i = 0; i < N; i++) {
        x[i] = (M - x[i]) % M;
        p[i] = (1 - p[i] + MOD) % MOD;
    }
    reverse(x.begin() + 1, x.end());
    reverse(p.begin() + 1, p.end());

    vector<int> ans2 = solveR();

    for(int i = 0; i < M; i++) {
        ans[i] = (ans[i] + ans2[(M - i) % M]) % MOD;
        if(i > 0) cout << " ";
        cout << ans[i];
    }
    cout << '\n';
}

int main() {
    ios::sync_with_stdio(false), cin.tie(nullptr);
    int T; cin >> T;
    while(T--) tc();
}

verbatim earliest root score=100 submission #70937


Dynamic Instability

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

Farmer Nhoj has trapped Bessie on a rooted tree with $N$ ($2\le N\le 2\cdot 10^5$) nodes, where node $1$ is the root. Scared and alone, Bessie makes the following move each second:

- If Bessie's current node has no children, then she will move to a random ancestor of the current node (excluding the node itself).
- Otherwise, Bessie will move to a random child of the current node.

Initially, Bessie is at node $x$, and her only way out is the exit located at node $y$ ($1\le x, y\le N$). For $Q$ ($1\le Q\le 2\cdot 10^5$) independent queries of $x$ and $y$, compute the expected number of seconds it would take Bessie to reach node $y$ for the first time if she started at node $x$, modulo $10^9 + 7$.

## Input Format

The first line contains $N$ and $Q$.

The next line contains $N - 1$ integers $p_2, \ldots, p_N$ describing the tree ($1\le p_i < i$). For each $2\le i\le N$, there is an edge between nodes $i$ and $p_i$.

Each of the next $Q$ lines contains integers $x$ and $y$ representing the nodes for that query.

## Output Format

For each query, output the expected number of seconds for Bessie to reach node $y$ for the first time starting at node $x$, modulo $10^9 + 7$.

## Examples

**Input 1**

```
5 5
1 2 2 1
1 1
2 1
3 1
4 1
5 1
```

**Output 1**

```
0
4
3
3
1
```

**Input 2**

```
5 5
1 2 2 1
1 1
1 2
1 3
1 4
1 5
```

**Output 2**

```
0
3
500000011
500000011
6
```

**Input 3**

```
13 10
1 2 2 4 3 1 5 6 4 7 8 10
1 12
10 6
5 12
1 13
13 10
6 4
7 12
3 1
12 8
2 1
```

**Output 3**

```
166666700
21
2
166666701
500000023
18
166666704
750000018
800000021
500000018
```

## Note

For the first example:

- In the 1st query, the expected time to reach node $1$ from itself is $0$.
- In the 3rd query, after $1$ second, Bessie will be at node $1$ with probability $\frac{1}{2}$ and at node $2$ with probability $\frac{1}{2}$. Since the expected time to reach node $1$ from node $2$ is $4$, the expected time for Bessie to reach node $1$ starting at node $3$ is $1 + \frac{1}{2}\cdot 0 + \frac{1}{2}\cdot 4 = 3$.

For the second example: in the 3rd query, the expected time to reach node $3$ from node $1$ is $\frac{15}{2}$.

## Scoring

- Inputs 4-8: For all queries, $y = 1$
- Inputs 9-13: For all queries, $x = 1$
- Inputs 14-18: For each $2\le i\le N$, $p_i$ is uniformly randomly chosen from the range $[1, i-1]$
- Inputs 19-23: No additional constraints

**Problem credits:** Avnith Vijayram

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int N = inf.readInt(2, 200000, "N"); inf.readSpace();
    int Q = inf.readInt(1, 200000, "Q"); inf.readEoln();
    for (int i = 2; i <= N; i++) {
        inf.readInt(1, i - 1, "p_i");   // 1 <= p_i < i
        if (i < N) inf.readSpace();
    }
    inf.readEoln();
    for (int q = 1; q <= Q; q++) {
        inf.readInt(1, N, "x"); inf.readSpace();
        inf.readInt(1, N, "y"); inf.readEoln();
    }
    inf.readEof();
    return 0;
}

#include <bits/stdc++.h>
using namespace std;

using ll = long long;
const int mxn = 2e5+5;
const ll M = 1e9+7;
ll modpow(ll x, ll p) {
    ll a = 1;
    while (p) {
        if (p & 1) a = a * x % M;
        x = x * x % M;
        p /= 2;
    }
    return a;
}
ll inv(ll x) {
    assert(x != 0);
    return modpow(x, M-2);
}

ll par[mxn];
vector<ll> childs[mxn];

ll d[mxn], up[mxn], e[mxn], esum[mxn], upd[mxn];

ll dfs1(int x, ll dep) {
    d[x] = dep;
    ll cx = childs[x].size();
    if (cx == 0) {
        up[x] = 1;
        return up[x];
    }

    ll upsum = 0;
    for (auto c : childs[x]) {
        upsum += dfs1(c, dep+1);
    }
    upsum %= M;

    if (dep > 0) {
        up[x] = (1 + inv(dep)) * (1 + inv(cx) * upsum % M) % M;
    }
    return up[x];
}

void dfs2(int x, ll cp, ll upcsum, ll ep, ll epsum, ll updsum) {
    ll downx = 0;
    if (x != 0) {
        downx = (cp + upcsum + (cp - 1) * (ep - inv(d[x]) * epsum % M)) % M;
        if (downx < 0) downx += M;
    }
    e[x] = (ep + downx) % M;
    esum[x] = (epsum + e[x]) % M;
    if (x > 0) updsum = (updsum + up[x] * inv(d[x]+1)) % M;
    upd[x] = updsum;

    ll cx = childs[x].size();
    ll upsum = 0;
    for (auto c : childs[x]) {
        upsum += up[c];
    }

    for (auto c : childs[x]) {
        dfs2(c, cx, (upsum + M - up[c]) % M, e[x], esum[x], upd[x]);
    }
}

int main() {
    int n, q; cin >> n >> q;
    for (int i = 1; i < n; i++) {
        int p; cin >> p; p--;
        childs[p].push_back(i);
        par[i] = p;
    }

    dfs1(0, 0);
    dfs2(0, 0, 0, 0, 0, 0);

    vector<vector<int>> jmp(18, vector<int>(n, -1));
    for (int i = 1; i < n; i++) jmp[0][i] = par[i];
    for (int j = 1; j < 18; j++) {
        for (int i = 0; i < n; i++) {
            int nx = jmp[j-1][i];
            if (nx != -1) nx = jmp[j-1][nx];
            jmp[j][i] = nx;
        }
    }

    auto jump = [&](int x, int l) -> int {
        for (int j = 17; j >= 0; j--) {
            if (x == -1) return x;
            if (l & (1 << j)) x = jmp[j][x];
        }
        return x;
    };

    while (q--) {
        int x, y; cin >> x >> y; x--; y--;

        int l;
        int nx = x, ny = y;
        if (d[nx] > d[ny]) nx = jump(nx, d[nx]-d[ny]);
        if (d[nx] < d[ny]) ny = jump(ny, d[ny]-d[nx]);
        if (nx == ny) l = nx;
        else {
            for (int j = 17; j >= 0; j--) {
                if (jmp[j][nx] != jmp[j][ny]) {
                    nx = jmp[j][nx];
                    ny = jmp[j][ny];
                }
            }
            assert(par[nx] == par[ny]);
            l = par[nx];
        }

        if (l == x) {
            cout << (e[y]-e[x]+M)%M << endl;
        } else {
            ll reachm = (up[x] + upd[par[x]] - upd[l] + M) % M;
            ll wtoy = (e[y] - (inv(d[l]+1) * esum[l] % M) + M) % M;
            cout << (reachm + wtoy) % M << endl;
        }
    }
}

verbatim earliest root score=100 submission #70938


Make All Distinct

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

You have an integer array $a_1\dots a_N$ with elements initially in the range $[1, N]$ ($1\le N\le 2\cdot 10^5$), as well as a nonzero integer $K$ ($-N\le K\le N$, $K\ne 0$).

You may perform the following operation as many times as you'd like (possibly zero): select an index $i$ and set $a_i = a_i + K$.

Find the minimum number of operations to make all array elements distinct.

## Input Format

The input consists of $T$ ($1\le T\le 10$) independent tests. Each test is described as follows:

The first line contains $N$ and $K$.

The second line contains $a_1\dots a_N$.

It is guaranteed that the sum of $N$ over all tests does not exceed $10^6$.

## Output Format

For each test, output a single line containing the minimum number of operations.

**Note:** The large size of integers involved in this problem may require the use of 64-bit integer data types (e.g., a `long long` in C/C++).

## Examples

**Input 1**

```
4
4 1
4 1 4 1
4 -3
4 1 4 1
4 4
4 1 4 1
3 -1
1 1 2
```

**Output 1**

```
2
4
2
1
```

## Note

For the first test, here is a possible sequence of two operations that makes all elements distinct.

```
4 1 4 1
5 1 4 1   (a_1 += 1)
5 1 4 2   (a_4 += 1)
```

## Scoring

- Inputs 2-4: $N\le 50$
- Inputs 5-7: $N\le 2000$
- Inputs 8-10: $K = 1$
- Inputs 11-13: No additional constraints

**Problem credits:** Akshaj Arora, Benjamin Qi

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 10, "T"); inf.readEoln();
    long long sumN = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(1, 200000, "N"); inf.readSpace();
        int K = inf.readInt(-N, N, "K"); inf.readEoln();
        ensuref(K != 0, "test %d: K must be nonzero", tc);
        sumN += N;
        for (int i = 1; i <= N; i++) { inf.readInt(1, N, "a_i"); if (i < N) inf.readSpace(); }
        inf.readEoln();
    }
    ensuref(sumN <= 1000000, "sum N %lld > 1e6", sumN);
    inf.readEof(); return 0;
}

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int T;
    cin >> T;
    for (int tc = 0; tc < T; ++tc) {
        int N, K;
        cin >> N >> K;
        vector<int> cnt(N);
        for (int i = 0; i < N; ++i) {
            int x;
            cin >> x;
            ++cnt.at(x - 1);
        }
        if (K < 0) {
            reverse(begin(cnt), end(cnt));
            K *= -1;
        }
        assert(0 < K && K <= N);
        int64_t ans = 0;

        for (int i = 0; i < K; ++i) {  // process remainder i mod K
            int64_t cur_min = i;
            int cnt_min = 0;
            while (cur_min < N || cnt_min > 0) {
                if (cur_min < N) cnt_min += cnt.at(cur_min);
                if (cnt_min > 0) ans += cnt_min - 1;
                cur_min += K;
                if (cnt_min > 0) --cnt_min;
            }
        }

        cout << ans << "\n";
    }
}

verbatim earliest root score=100 submission #70958


Strange Function

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

For all positive integers $x$, the function $f(x)$ is defined as follows:

- If $x$ has any digits that aren't $0$ or $1$, for each digit of $x$, set it to $1$ if it is odd or $0$ otherwise, and return $x$.
- Otherwise, return $x - 1$.

Given a value of $x$ ($1\le x < 10^{2\cdot 10^5}$), find how many times $f$ needs to be applied to $x$ until $x$ reaches $0$. As this number might be very large, output its remainder when divided by $10^9 + 7$.

## Input Format

The first line contains $T$ ($1\le T\le 10^5$), the number of independent tests.

The next $T$ lines each contain a positive integer $x$ consisting solely of the digits $0$-$9$, with no leading zeros.

It is guaranteed that the total number of digits in all input integers does not exceed $10^6$.

## Output Format

For each test case, output the remainder of the number of times when divided by $10^9 + 7$ on a separate line.

## Examples

**Input 1**

```
2
24680
210
```

**Output 1**

```
1
4
```

**Input 2**

```
1
1234567890123456789012345678901234567890
```

**Output 2**

```
511620083
```

## Note

For the first example:

- First test: $x$ becomes zero after one operation.
- Second test: $f(x) = 10$, $f^2(x) = 9$, $f^3(x) = 1$, $f^4(x) = 0$.

## Scoring

- Inputs 3-5: $T\le 2000$, $x < 10^9$
- Inputs 6-7: $x < 10^{18}$
- Inputs 8-9: $x < 10^{60}$
- Inputs 10-12: No additional constraints

**Problem credits:** Aidan Bai

#include "testlib.h"
#include <string>
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 100000, "T"); inf.readEoln();
    long long totDigits = 0;
    for (int tc = 1; tc <= T; tc++) {
        std::string x = inf.readToken();
        int len = (int)x.size();
        ensuref(len >= 1, "test %d: empty number", tc);
        for (char c : x) ensuref(c >= '0' && c <= '9', "test %d: non-digit '%c'", tc, c);
        // positive integer, no leading zeros
        ensuref(!(len > 1 && x[0] == '0'), "test %d: leading zero", tc);
        ensuref(!(len == 1 && x[0] == '0'), "test %d: x must be positive", tc);
        totDigits += len;
        inf.readEoln();
    }
    ensuref(totDigits <= 1000000, "total digits %lld > 1e6", totDigits);
    inf.readEof(); return 0;
}

#include "bits/extc++.h"

using namespace std;

using ll = long long;

#define sz(x) int(std::size(x))

constexpr ll mod = 1e9+7;

void solve(){
    string s;
    cin>>s;
    ll moves=0;
    int n=sz(s);
    ll tpow[n]{}; // powers of 2
    tpow[0]=1;
    for(int i = 1; i<n; i++){
        tpow[i]=(tpow[i-1]*2)%mod;
    }
    {
        // first make all digits 0 or 1
        bool all01=1;
        for(auto u: s){
            if(u!='0' && u!='1'){
                all01=0;
                break;
            }
        }
        if(!all01){
            moves++;
            for(auto &u: s){
                u=char(((u-'0')%2)+'0');
            }
        }
    }
    reverse(s.begin(),s.end());
    for(int i = 0; i<n; i++){
        if(s[i]=='1'){
            if(i==0)moves++;
            else{
                moves=(moves+tpow[i]+tpow[i-1])%mod;
            }
        }
    }
    cout<<moves<<"\n";
}

int main(){
    cin.tie(0)->sync_with_stdio(0);
    cin.exceptions(ios::failbit);
    int t;
    cin>>t;
    while(t--)solve();
}

verbatim earliest root score=100 submission #70959


Swap to Win

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

Farmer John has a favorite string $t$ with $M$ characters. He also has $N$ strings $s_1, s_2, \ldots, s_N$ each with $M$ characters ($1\le N, M\le 1000$).

FJ can perform the following two types of operations:

1. FJ chooses any string $s_x$ and two indices $p$ and $q$. Then, he swaps the $p$-th and $q$-th character of $s_x$ ($1\le x\le N$, $1\le p, q\le M$).
2. FJ chooses two strings $s_x$ and $s_y$ and an index $k$. Then, he swaps the $k$-th characters of $s_x$ and $s_y$ ($1\le x, y\le N$, $1\le k\le M$).

His goal is to make $s_1$ equal to $t$. Find any series of operations that fulfills his goal. Because FJ is in a hurry, he only has time to perform a total of $2M$ operations. The inputs guarantee that it is possible to fulfill FJ's goal.

## Input Format

The first line contains $T$ ($1\le T\le 10$), the number of independent tests. Each test is specified in the following format:

The first line contains $N$ and $M$.

The second line contains $t$.

Then, $N$ lines follow, the $i$-th of which contains $s_i$.

The inputs will guarantee that it is possible to fulfill FJ's goal. All strings contain lowercase English letters (a-z).

## Output Format

The output for each test should be as follows:

On the first line, output an integer $K$, the number of operations you will perform. $K$ must be a non-negative integer less than or equal to $2M$.

Then, output $K$ lines, denoting the operations you will perform in sequential order. Each line should be one of the following:

- `1 x p q`
- `2 x y k`

## Examples

**Input 1**

```
3
3 6
banana
nabana
banana
nnbaaa
5 3
abc
def
bca
ghi
jkl
mno
3 5
abcde
abcde
abcde
zzzzz
```

**Output 1**

```
3
2 1 2 1
1 1 3 5
2 1 2 5
5
1 2 1 3
2 1 2 1
1 2 2 3
2 1 2 2
2 1 2 3
0
```

## Note

Here is how $s$ changes according to the first test's output (with letters swapped in uppercase):

```
nabana    Babana    baNaBa    banaNa
banana -> Nanana -> nanana -> nanaBa
nnbaaa    nnbaaa    nnbaaa    nnbaaa
```

After all three operations, $s_1 = t$.

## Scoring

- Inputs 2-6: $N, M\le 100$
- Inputs 7-12: No additional constraints

**Problem credits:** Chongtian Ma

#include "testlib.h"
#include <string>
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 10, "T"); inf.readEoln();
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(1, 1000, "N"); inf.readSpace();
        int M = inf.readInt(1, 1000, "M"); inf.readEoln();
        std::string t = inf.readLine();
        ensuref((int)t.size() == M, "test %d: |t|=%d expected %d", tc, (int)t.size(), M);
        for (char c : t) ensuref(c >= 'a' && c <= 'z', "test %d t: non-lowercase '%c'", tc, c);
        for (int i = 1; i <= N; i++) {
            std::string s = inf.readLine();
            ensuref((int)s.size() == M, "test %d s_%d: len %d expected %d", tc, i, (int)s.size(), M);
            for (char c : s) ensuref(c >= 'a' && c <= 'z', "test %d s_%d: non-lowercase '%c'", tc, i, c);
        }
    }
    inf.readEof(); return 0;
}

#include <bits/stdc++.h>
using namespace std;

void solve() {
    int n, m;
    cin >> n >> m;

    string t;
    cin >> t;

    vector<string> s(n);
    for (int i = 0; i < n; i++) cin >> s[i];

    vector<vector<int>> has(n, vector<int>(26, 0));

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            has[i][s[i][j] - 'a']++;
        }
    }

    vector<array<int, 4>> ops;

    auto op = [&](int type, int a, int b, int c) {
        // store 1-indexed for printing
        ops.push_back({type, a + 1, b + 1, c + 1});

        if (type == 1) {
            swap(s[a][b], s[a][c]);
        } else {
            has[a][s[a][c] - 'a']--;
            has[b][s[b][c] - 'a']--;
            swap(s[a][c], s[b][c]);
            has[a][s[a][c] - 'a']++;
            has[b][s[b][c] - 'a']++;
        }
    };

    // Swap within s1 to fix as many positions as possible
    for (int i = 0; i < m; i++) {
        if (s[0][i] != t[i]) {
            for (int j = 0; j < m; j++) {
                if (s[0][j] == t[i] && s[0][j] != t[j]) {
                    op(1, 0, i, j);
                    break;
                }
            }
        }
    }

    // Import needed characters from other rows
    for (int i = 0; i < m; i++) {
        if (s[0][i] != t[i]) {
            for (int j = 1; j < n; j++) {
                if (has[j][t[i] - 'a']) {
                	// find the column
                    int idx = int(find(s[j].begin(), s[j].end(), t[i]) - s[j].begin());
                    op(1, j, i, idx);
                    op(2, 0, j, i);
                    break;
                }
            }
        }
    }

    printf("%d\n", (int)ops.size());
    for (auto &v : ops) {
        printf("%d %d %d %d\n", v[0], v[1], v[2], v[3]);
    }
}

int main() {
    cin.tie(0) -> sync_with_stdio(0);

    int T;
    cin >> T;
    while (T--) solve();
    return 0;
}

#include "testlib.h"
#include <vector>
#include <string>
using namespace std;

int main(int argc, char *argv[]) {
    setName("USACO 2026 Bronze: Swap to Win");
    registerTestlibCmd(argc, argv);

    int T = inf.readInt();
    for (int t = 1; t <= T; t++) {
        int N = inf.readInt();
        int M = inf.readInt();
        string target = inf.readToken();
        if ((int)target.size() != M)
            quitf(_fail, "judge input malformed at test %d (target len)", t);
        vector<string> s(N + 1);
        for (int i = 1; i <= N; i++) {
            s[i] = inf.readToken();
            if ((int)s[i].size() != M)
                quitf(_fail, "judge input malformed at test %d (s_%d len)", t, i);
        }

        // also consume reference output's K and its K op lines (we don't need them for verification)
        int refK = ans.readInt();
        for (int j = 0; j < refK; j++) {
            int op = ans.readInt();
            if (op == 1) { ans.readInt(); ans.readInt(); ans.readInt(); }
            else if (op == 2) { ans.readInt(); ans.readInt(); ans.readInt(); }
            else quitf(_fail, "reference output malformed at test %d", t);
        }

        int K = ouf.readInt(0, 2 * M, "K");
        for (int j = 0; j < K; j++) {
            int op = ouf.readInt(1, 2, "op type");
            if (op == 1) {
                int x = ouf.readInt(1, N, "x");
                int p = ouf.readInt(1, M, "p");
                int q = ouf.readInt(1, M, "q");
                swap(s[x][p - 1], s[x][q - 1]);
            } else {
                int x = ouf.readInt(1, N, "x");
                int y = ouf.readInt(1, N, "y");
                int k = ouf.readInt(1, M, "k");
                swap(s[x][k - 1], s[y][k - 1]);
            }
        }

        if (s[1] != target)
            quitf(_wa, "test %d: after %d operations s_1='%s' (expected '%s')",
                  t, K, s[1].c_str(), target.c_str());
    }

    if (!ouf.seekEof())
        quitf(_wa, "extra tokens in contestant output");
    quitf(_ok, "T=%d cases", T);
}

verbatim earliest root score=100 submission #70973


Clash!

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

Farmer John is playing a famous and strategic card game with his dear cow Bessie. FJ has $N$ ($2\le N\le 2\cdot 10^5$) cards, conveniently numbered from $1$ to $N$. The $i$-th card costs $a_i$ ($1\le a_i\le 10^9$) moolixir if FJ wants to play it.

His hand always consists of $H$ cards at any given time ($1\le H < N$). Initially, his hand consists of cards $1$ through $H$. The remaining cards are in a draw queue. Every time FJ plays a card in his hand, he will draw its replacement from the front of the draw queue to his hand. Then, FJ will put the card he just played to the back of the draw queue. Initially, cards $H + 1$ through $N$ are arranged from the front to the back of the draw queue in that order.

In this game, time is measured in integer seconds. Initially, the game starts at time $0$ with FJ having $0$ moolixir. Immediately before each of integer times $t = 1, 2, 3, \dots$, moolixir increases by $1$. At each integer time, FJ may choose to play a card in his hand if its cost does not exceed FJ's current moolixir count, which subtracts FJ's current moolixir count by the card's cost.

FJ marks a subset of his cards $s_1, s_2, \ldots, s_k$ as win-conditions ($1\le k\le N$, $1\le s_i\le N$). If FJ has at least one win-condition in his hand, the next card he plays must be a win-condition.

He asks you $Q$ ($1\le Q\le 2\cdot 10^5$) queries. Each query is of the following form: what is the maximum number of win-conditions he could have placed down within $t$ time ($1\le t\le 10^{18}$)?

## Input Format

The first line contains $N$ and $H$.

The second line contains $N$ integers $a_1, a_2, \ldots, a_N$.

The third line contains an integer $k$, the number of win-conditions.

The fourth line contains $k$ distinct integers $s_1, s_2, \ldots, s_k$.

The fifth line contains an integer $Q$.

The following $Q$ lines each contain an integer $t$, the time to answer for each query.

## Output Format

For each query, output the maximum number of win-conditions that FJ could've put down within $t$ time.

## Examples

**Input 1**

```
6 3
2 4 3 5 7 6
2
1 4
6
1
2
3
7
10
1000000000000000
```

**Output 1**

```
0
1
1
2
2
142857142857143
```

## Note

In this case, you start with card $1$, a win condition on your hand. You can play it after you accumulate $2$ elixir in $2$ seconds. This means that just after $t = 1$ you can play no cards, but after $t = 2$ you can play your first card, which must be your win condition.

After $t = 3$, it is still most optimal to play card $1$ and have $1$ elixir remaining, so the answer here is still $1$.

You then draw card $4$, which is also a win condition. You play it immediately after $t = 7$, so you have played $2$ win conditions at this time.

You then draw card $5$ and have no win conditions in your hand. After $t = 10$, even if you play card $3$ with the $3$ elixir you have, your number of win conditions does not change.

## Scoring

- Inputs 2-3: $N, Q\le 100$
- Inputs 4-5: $H = 1$
- Inputs 6-11: No additional constraints

**Problem credits:** Chongtian Ma

#include "testlib.h"
#include <set>
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int N = inf.readInt(2, 200000, "N"); inf.readSpace();
    int H = inf.readInt(1, N - 1, "H"); inf.readEoln();
    for (int i = 1; i <= N; i++) { inf.readInt(1, 1000000000, "a_i"); if (i < N) inf.readSpace(); }
    inf.readEoln();
    int k = inf.readInt(1, N, "k"); inf.readEoln();
    std::set<int> seen;
    for (int i = 1; i <= k; i++) {
        int s = inf.readInt(1, N, "s_i");
        ensuref(seen.insert(s).second, "win-condition %d repeats", s);
        if (i < k) inf.readSpace();
    }
    inf.readEoln();
    int Q = inf.readInt(1, 200000, "Q"); inf.readEoln();
    for (int q = 1; q <= Q; q++) { inf.readLong(1, 1000000000000000000LL, "t"); inf.readEoln(); }
    inf.readEof(); return 0;
}

#include <bits/stdc++.h>
using namespace std;

template <class T> using V = vector<T>;
#define all(x) begin(x), end(x)

using ll = long long;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int N, H;
    cin >> N >> H;

    using P = pair<int, int>;
    V<P> A(N);
    for (auto &p : A) cin >> p.second;

    int K;
    cin >> K;
    for (int i = 0; i < K; ++i) {
        int s;
        cin >> s;
        --s;
        A.at(s).first = -1;
    }

    priority_queue<P, V<P>, greater<P>> pq;

    for (int i = 0; i < H - 1; ++i) pq.push(A.at(i));
    V<ll> cycle;  // time each win-condition in cycle is played
    ll cycle_len = 0;
    for (int i = 0; i <= N - H; ++i) {
        pq.push(A.at(i + H - 1));
        cycle_len += pq.top().second;
        if (pq.top().first == -1) cycle.push_back(cycle_len);
        pq.pop();
    }
    int Q;
    cin >> Q;
    for (int i = 0; i < Q; ++i) {
        ll t;
        cin >> t;
        ll ans = t / cycle_len * size(cycle);
        ans +=
            upper_bound(begin(cycle), end(cycle), t % cycle_len) - begin(cycle);
        cout << ans << "\n";
    }
}

verbatim earliest root score=100 submission #70955


Milk Buckets

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

There are $N$ ($1\le N\le 2\cdot 10^5$) buckets in a stack where the $i$-th bucket from the top has capacity $a_i$ gallons ($1\le a_i\le 10^9$). A tap above the top bucket sends one gallon of milk per second into the first bucket per second. There is also a pool below bucket $N$.

When a bucket reaches its capacity after $t$ seconds, at the start of the $(t+1)$-th second it flips to dump its contents into either the bucket below if it is not the last bucket or the pool otherwise (it reverts back to filling at the end of the $(t+1)$-th second). A bucket cannot collect milk while it is flipped; any milk arriving at the bucket above during this second is lost. Additionally, any amount of milk exceeding the capacity of the bucket below is lost.

Handle $Q$ ($1\le Q\le 3\cdot 10^5$) queries, each specified by three integers $i$, $v$, and $t$:

- First, set $a_i = v$ ($1\le i\le N$, $1\le v\le 10^9$).
- Then answer the following question: Suppose that at time $0$, all buckets as well as the pool are empty. Determine the number of gallons of milk in the pool after $t$ seconds ($1\le t\le 10^{18}$).

The $a_i = v$ updates persist through later queries.

## Input Format

The first line contains $N$.

The second line contains $a_1\dots a_N$.

The next line contains $Q$.

Then the following $Q$ lines contain three integers $i$, $v$, and $t$. This means that you should set $a_i = v$ and then answer the question for $t$.

## Output Format

Output the answer to each question on a separate line.

## Examples

**Input 1**

```
3
1 1 1
30
1 1 1
1 1 2
1 1 3
1 1 4
1 1 5
1 1 6
1 1 7
1 1 8
1 1 9
1 1 10
1 2 1
1 2 2
1 2 3
1 2 4
1 2 5
1 2 6
1 2 7
1 2 8
1 2 9
1 2 10
2 2 1
2 2 2
2 2 3
2 2 4
2 2 5
2 2 6
2 2 7
2 2 8
2 2 9
2 2 10
```

**Output 1**

```
0
0
0
1
1
2
2
3
3
4
0
0
0
0
1
1
1
2
2
2
0
0
0
0
1
1
1
2
2
2
```

**Input 2**

```
2
1 2
10
1 1 1
1 1 2
1 1 3
1 1 4
1 1 5
1 1 6
1 1 7
1 1 8
1 1 9
1 1 10
```

**Output 2**

```
0
0
0
0
2
2
2
2
4
4
```

**Input 3**

```
3
1 1 1
1
1 1 1000000000000000000
```

**Output 3**

```
499999999999999999
```

## Note

When $a = [1, 1, 1]$:

- Bucket $1$ flips at times $2, 4, 6, \dots$
- Bucket $2$ flips at times $3, 5, 7, \dots$
- Bucket $3$ flips at times $4, 6, 8, \dots$

When $a = [2, 1, 1]$:

- Bucket $1$ flips at times $3, 6, 9, \dots$
- Bucket $2$ flips at times $4, 7, 10, \dots$
- Bucket $3$ flips at times $5, 8, 11, \dots$

When $a = [2, 2, 1]$:

- Bucket $1$ flips at times $3, 6, 9, \dots$
- Bucket $2$ flips at times $4, 7, 10, \dots$
- Bucket $3$ flips at times $5, 8, 11, \dots$

## Scoring

- Inputs 4-5: $N\le 10$, $Q\le 100$, and all $t\le 10^4$
- Inputs 6-11: $N\le 10^3$, $Q\le 10^4$
- Inputs 12-23: No additional constraints

**Problem credits:** Akshaj Arora

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int N = inf.readInt(1, 200000, "N"); inf.readEoln();
    for (int i = 1; i <= N; i++) { inf.readInt(1, 1000000000, "a_i"); if (i < N) inf.readSpace(); }
    inf.readEoln();
    int Q = inf.readInt(1, 300000, "Q"); inf.readEoln();
    for (int q = 1; q <= Q; q++) {
        inf.readInt(1, N, "i"); inf.readSpace();
        inf.readInt(1, 1000000000, "v"); inf.readSpace();
        inf.readLong(1, 1000000000000000000LL, "t"); inf.readEoln();
    }
    inf.readEof(); return 0;
}

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

int cdiv(int a, int b) { return (a + b - 1) / b; }

const ll mx = 1e18;

void solve() {
    int n;
    cin >> n;
    vector<int> a(n);
    for (auto &i : a) cin >> i;

    // precomp
    set<int> s;
    auto upd = [&](int i) {
        if (i != 0 && a[i] > a[i - 1]) s.insert(i);
        else s.erase(i);
    };
    for (int i = 1; i < n; i++) upd(i);

    // solve
    int q;
    cin >> q;
    while (q--) {
        ll i, v, t;
        cin >> i >> v >> t;
        a[--i] = v;
        upd(i);
        if (i < n - 1) upd(i + 1);

        ll ans = max(0LL, t - n + 1);
        ans /= a[0] + 1;
        for (int i : s) {
            ll r = cdiv(a[i], a[i - 1]);
            ans /= r;
            if (ans == 0) break;
        }
        ans *= a.back();
        cout << ans << '\n';
    }
}

signed main() {
    cin.tie(0)->sync_with_stdio(0);
    solve();
}

verbatim earliest root score=100 submission #70956


Point Elimination

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

You have $N$ ($2\le N\le 10^5$, $N$ is even) points $(x_i, y_i)$ ($1\le x_i, y_i\le 10^6$) on an infinite 2D-coordinate plane.

You can perform the following two types of operations any number of times:

- Choose two points that are directly adjacent to each other (Manhattan distance of $1$), and remove both points.
- Choose any two points and swap their $y$-coordinates. Formally, points $(a, b)$ and $(c, d)$ become $(a, d)$ and $(c, b)$ respectively.

Determine if it is possible to eliminate all points on the board. Note that it may be the case that two points may map to the same coordinate; they should still be treated as different points. You also may not directly delete points on the same coordinate, as they are technically not directly adjacent.

## Input Format

The first line contains $T$ ($1\le T\le 5000$), the number of test cases.

The first line of each test case contains an integer $N$.

The following $N$ lines contain two integers $x_i$ and $y_i$.

It is guaranteed that the sum of $N$ over all test cases does not exceed $5\cdot 10^5$.

## Output Format

For each test case, output `YES` or `NO` on a new line.

## Examples

**Input 1**

```
4
2
1 1
1 1
4
6 10
7 11
8 1
8 1
6
1 2
1 3
1 4
1 5
10 10
11 10
6
1 1
1 1
1 1
1 1
10 10
11 11
```

**Output 1**

```
NO
YES
YES
NO
```

## Note

For the first test, the only two points are equal, so no swaps will do anything. Thus, our answer is `NO`.

In the second test, we can swap the $y$-coordinates of $6$ and $7$ with $8$ and $8$. Then, we can remove the first two points (horizontal adjacency) and the last two (vertical).

For the third test, no swaps are needed. We can remove the first pair, second, and third.

In the last test, it can be shown that no matter how we swap the $y$-coordinates, we will never be able to remove all the points in adjacent pairs.

## Scoring

- Input 2: $T\le 1000$, $N\le 6$
- Inputs 3-5: $N\le 100$
- Inputs 6-11: No additional constraints

**Problem credits:** Alex Pylypenko, Chongtian Ma

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 5000, "T"); inf.readEoln();
    long long sumN = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(2, 100000, "N"); inf.readEoln();
        ensuref(N % 2 == 0, "test %d: N must be even, got %d", tc, N);
        sumN += N;
        for (int i = 1; i <= N; i++) {
            inf.readInt(1, 1000000, "x"); inf.readSpace();
            inf.readInt(1, 1000000, "y"); inf.readEoln();
        }
    }
    ensuref(sumN <= 500000, "sum N %lld > 5e5", sumN);
    inf.readEof(); return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define int int64_t
using vi = vector<int>;
using pi = array<int, 2>;
#define all(x) x.begin(), x.end()
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define nl '\n'

void solve() {
    int n; cin >> n;
    vi x(n), y(n);
    FOR(i, 0, n) cin >> x[i] >> y[i];
    sort(all(x));
    sort(all(y));
    for (int i = 0; i < n; i += 2) {
        if (x[i + 1] - x[i] >= 2
            or y[i + 1] - y[i] >= 2) {
                cout << "NO" << nl;
                return;
            }
    }
    auto get_range = [&] (vi v) -> pi {
        int lo = 0;
        for (int i = 0; i < n; i += 2) {
            lo += v[i] != v[i + 1];
        }
        int hi = 0;
        map<int, int> m;
        FOR(i, 0, n) m[v[i]]++;
        while (m.size()) {
            auto [i, c] = *m.begin();
            if (m.count(i + 1)) {
                int d = min(c, m[i + 1]);
                if ((m[i] - d) & 1) d--;
                m[i + 1] -= d;
                m[i] -= d;
                hi += d;
            }
            m.erase(i);
        }
        return {lo, hi};
    };
    auto [xl, xr] = get_range(x);
    auto [yl, yr] = get_range(y);
    for (int i = xl; i <= xr; i += 2) {
        if (clamp(n / 2 - i, yl, yr) == n / 2 - i) {
            if ((n / 2 - i) % 2 == yl % 2) {
                cout << "YES" << nl;
                return;
            }
        }
    }
    cout << "NO" << nl;
}

signed main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int t; cin >> t; while (t--) solve();
}

verbatim earliest root score=100 submission #70967


Good Cyclic Shifts

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

For a permutation $p_1, p_2, \dots, p_N$ of $1\dots N$ ($1\le N\le 2\cdot 10^5$), let $f(p) = \sum_{i=1}^N \frac{|p_i - i|}{2}$. A permutation is *good* if it can be turned into the identity permutation using at most $f(p)$ swaps of adjacent elements.

Given a permutation, find which cyclic shifts of it are good.

## Input Format

The input consists of $T$ ($1\le T\le 10^5$) independent tests. Each test is specified as follows:

The first line contains $N$.

The second line contains $p_1, p_2, \dots, p_N$ ($1\le p_i\le N$), which is guaranteed to be a permutation of $1\dots N$.

It is guaranteed that the sum of $N$ over all tests does not exceed $10^6$.

## Output Format

For each test, output two lines:

- On the first line, output the number of good cyclic shifts $k$.
- Then output a line with $k$ space-separated integers $s$ ($0\le s < N$) in increasing order, meaning that $p$ is good when cyclically shifted to the right $s$ times.

## Examples

**Input 1**

```
3
5
5 4 3 2 1
4
1 2 4 3
5
1 2 3 4 5
```

**Output 1**

```
0

2
0 1
5
0 1 2 3 4
```

## Note

Consider the second test case, where $p = [1, 2, 4, 3]$.

$f(p) = (|1 - 1| + |2 - 2| + |4 - 3| + |3 - 4|) / 2 = 1$. Since $p$ can be turned into the identity permutation in one move by swapping $p_3$ and $p_4$, $p$ is good.

Cyclically shifting $p$ to the right $1$ time, we get $q = [3, 1, 2, 4]$. $f(q) = (|3 - 1| + |1 - 2| + |2 - 3| + |4 - 4|) / 2 = 2$. Since $q$ can be turned into the identity permutation in two moves by swapping $q_1$ two steps forward, $q$ is good.

It can be seen that the other two cyclic shifts are not good.

## Scoring

- Input 2: $N\le 10$
- Inputs 3-5: $T\le 10$, $N\le 2000$
- Inputs 6-11: No additional constraints

**Problem credits:** Akshaj Arora

#include "testlib.h"
#include <set>
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 100000, "T"); inf.readEoln();
    long long sumN = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(1, 200000, "N"); inf.readEoln();
        sumN += N;
        std::set<int> seen;
        for (int i = 1; i <= N; i++) {
            int p = inf.readInt(1, N, "p_i");
            ensuref(seen.insert(p).second, "test %d: not a permutation, %d repeats", tc, p);
            if (i < N) inf.readSpace();
        }
        inf.readEoln();
    }
    ensuref(sumN <= 1000000, "sum N %lld > 1e6", sumN);
    inf.readEof(); return 0;
}

#include <bits/stdc++.h>
using namespace std;

void solve() {
  int n;
  cin >> n;
  vector<int> p(n);
  for (auto &i : p)
    cin >> i;

  // solve
  stack<int> s;
  vector<int> nl(n, -1);
  for (int j = 0; j < 2; j++) {
    for (int i = 0; i < n; i++) {
      while (s.size() && p[i] >= p[s.top()])
        s.pop();
      if (j == 1 && s.size())
        nl[i] = s.top();
      s.push(i);
    }
  }
  while (s.size())
    s.pop();
  vector<int> nr(n, -1);
  for (int j = 0; j < 2; j++) {
    for (int i = n - 1; i >= 0; i--) {
      while (s.size() && p[i] <= p[s.top()])
        s.pop();
      if (j == 1 && s.size())
        nr[i] = s.top();
      s.push(i);
    }
  }

  vector<int> ps(2 * n + 1);
  for (int i = 0; i < n; i++) {
    int l = nl[i], r = nr[i];
    if (min(l, r) == -1)
      continue;
    if ((l < i) ^ (i < r) ^ (l < r)) {
      if (l < r)
        l += n;
      ps[r + 1]++;
      ps[l + 1]--;
    }
  }
  for (int i = 1; i <= 2 * n; i++)
    ps[i] += ps[i - 1];
  vector<int> ans;
  for (int i = 1; i <= n; i++) {
    if (max(ps[i], ps[i + n]) == 0)
      ans.push_back(n - i);
  }
  reverse(ans.begin(), ans.end());

  // ans
  int m = size(ans);
  cout << m << '\n';
  for (int i = 0; i < m; i++)
    cout << ans[i] << " \n"[i == m - 1];
  if (m == 0)
    cout << "\n";
}

signed main() {
  cin.tie(0)->sync_with_stdio(0);
  int t = 1;
  cin >> t;
  while (t--)
    solve();
}

verbatim earliest root score=100 submission #70951


Picking Flowers

**Time limit:** 3 seconds    **Memory limit:** 256 megabytes

> **Note:** The time limit for this problem is 3s, 1.5x the default.

## Description

Farmer John's farm structure can be represented as a connected undirected graph with $N$ vertices and $M$ unweighted edges ($2\le N\le 2\cdot 10^5$, $N - 1\le M\le 2\cdot 10^5$). Initially, Farmer John is at his barn, represented by farm $1$.

Initially, farms $s_1, s_2, \ldots, s_K$ contain flower fields and farms $d_1, d_2, \ldots, d_L$ are destination farms. FJ calls a path *pretty* if:

- It starts at farm $1$.
- It ends at some destination farm $x$.
- There is no shorter path starting at farm $1$ and ending at farm $x$.
- FJ visits all flower fields along the way.

FJ can wave his magic wand and make up to one more farm contain a flower field (if it doesn't already). However, FJ isn't very decisive. For farms $f$ numbered $2$ through $N$, after FJ temporarily makes farm $f$ contain a flower field, determine if there exists a pretty path.

Note that there are multiple test cases, and each case must be treated independently.

## Input Format

The first line contains $T$ ($1\le T\le 100$), the number of independent test cases.

The first line of each test case contains $N$, $M$, $K$, and $L$ ($0\le K\le N-1$, $1\le L\le N-1$).

The following line contains $s_1, s_2, \ldots, s_K$ ($2\le s_i\le N$, $s_i$ are all distinct).

The following line contains $d_1, d_2, \ldots, d_L$ ($2\le d_i\le N$, $d_i$ are all distinct).

The following $M$ lines contain $u$ and $v$, denoting there is an undirected edge between farms $u$ and $v$. All edges are considered to have equal length. It is guaranteed that there aren't any multi-edges or self-loops.

It is guaranteed that both the sum of $N$ and the sum of $M$ do not exceed $10^6$ over all test cases.

## Output Format

For each test case, output a binary string of length $N - 1$. The $i$-th character in the string should be $1$ if the answer holds true for the $(i+1)$-th farm.

## Examples

**Input 1**

```
1
7 7 0 1

5
1 2
2 3
3 4
4 5
5 6
6 7
3 6
```

**Output 1**

```
111110
```

**Input 2**

```
1
6 6 0 2

5 3
1 2
2 3
3 4
4 5
5 6
2 5
```

**Output 2**

```
11010
```

**Input 3**

```
3
4 3 2 1
2 3
4
1 2
2 3
3 4
4 4 2 1
2 3
4
1 2
1 3
2 4
3 4
5 5 2 1
2 4
5
1 2
1 3
2 4
3 4
4 5
```

**Output 3**

```
111
000
1011
```

## Note

For the first example, since $5$ is the only destination farm, the answer holds true if the $i$-th farm lies on any shortest path from $1$ to $5$. There are two shortest paths from $1$ to $5$: $1\to 2\to 3\to 4\to 5$ and $1\to 2\to 3\to 6\to 5$. Since there are no farms that already contain flower fields, the answer for farm $i$ holds true if farm $i$ lies on at least one of the two aforementioned paths.

For the second example, there are two destination farms: $5$ and $3$. Since there are no farms that already contain flower fields, the $i$-th farm must lie on a shortest path to either $5$ or $3$.

For the first test of the third example, the answer holds true for the $i$-th farm if FJ can pass through farm $i$, farm $2$, and farm $3$ (in no particular order) on some shortest path to farm $4$. It can be shown that the answer holds true for all farms.

## Scoring

- Inputs 4-6: $K = 0$ and $L = 1$
- Inputs 7-9: $K = 0$
- Inputs 10-23: No additional constraints

**Problem credits:** Chongtian Ma

#include "testlib.h"
#include <set>
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 100, "T"); inf.readEoln();
    long long sumN = 0, sumM = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(2, 200000, "N"); inf.readSpace();
        int M = inf.readInt(N - 1, 200000, "M"); inf.readSpace();
        int K = inf.readInt(0, N - 1, "K"); inf.readSpace();
        int L = inf.readInt(1, N - 1, "L"); inf.readEoln();
        sumN += N; sumM += M;
        std::set<int> sset;
        for (int i = 1; i <= K; i++) {
            int s = inf.readInt(2, N, "s_i");
            ensuref(sset.insert(s).second, "test %d: s %d repeats", tc, s);
            if (i < K) inf.readSpace();
        }
        inf.readEoln();
        std::set<int> dset;
        for (int i = 1; i <= L; i++) {
            int d = inf.readInt(2, N, "d_i");
            ensuref(dset.insert(d).second, "test %d: d %d repeats", tc, d);
            if (i < L) inf.readSpace();
        }
        inf.readEoln();
        for (int e = 1; e <= M; e++) {
            int u = inf.readInt(1, N, "u"); inf.readSpace();
            int v = inf.readInt(1, N, "v"); inf.readEoln();
            ensuref(u != v, "test %d edge %d: self-loop not allowed", tc, e);
        }
    }
    ensuref(sumN <= 1000000, "sum N %lld > 1e6", sumN);
    ensuref(sumM <= 1000000, "sum M %lld > 1e6", sumM);
    inf.readEof(); return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define int int64_t
using vi = vector<int>;
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define all(x) x.begin(), x.end()
#define nl '\n'

void solve() {
    int n, m, k, l; cin >> n >> m >> k >> l;
    vector<int> s(k); for (auto& i : s) cin >> i;
    vector<int> d(l); for (auto& i : d) cin >> i;
    vector<vi> g(n + 1);
    FOR(_, 0, m) {
        int u, v; cin >> u >> v;
        g[u].push_back(v); g[v].push_back(u);
    }
    vi layer[n];
    queue<int> q; q.push(1);
    vi dist(n + 1, -1); dist[1] = 0;
    while (q.size()) {
        int u = q.front(); q.pop();
        layer[dist[u]].push_back(u);
        for (int v : g[u]) if (dist[v] == -1) {
            dist[v] = dist[u] + 1;
            q.push(v);
        }
    }
    vi flower(n);
    int mx = 0;
    for (int i : s) {
        mx = max(mx, dist[i]);
        if (flower[dist[i]]) {
            cout << string(n - 1, '0') << nl;
            return;
        }
        flower[dist[i]] = i;
    }
    vi dp(n + 1);
    for (int i : d) {
        if (dist[i] > mx) dp[i] = 1;
        if (dist[i] == mx and flower[dist[i]]) dp[i] = 1;
    }
    for (int l = n - 2; l >= 0; l--) {
        for (int i : layer[l]) for (int j : g[i])
            if (flower[l + 1]) {
                if (j == flower[l + 1]) dp[i] |= dp[j];
            } else {
                if (dist[i] + 1 == dist[j]) dp[i] |= dp[j];
            }
    }
    vi dp2(n + 1);
    dp2[1] = 1;
    FOR(l, 0, n - 1) {
        for (int i : layer[l]) for (int j : g[i])
            if (flower[l + 1]) {
                if (j == flower[l + 1]) dp2[j] |= dp2[i];
            } else {
                if (dist[i] + 1 == dist[j]) dp2[j] |= dp2[i];
            }
    }
    FOR(i, 2, n + 1) cout << "01"[dp[i] and dp2[i]];
    cout << nl;
}

signed main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int t; cin >> t; while (t--) solve();
}

verbatim earliest root score=100 submission #70986


Random Tree Generation

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

Suppose the function $\text{randint}(l, r)$ returns an integer independently and uniformly at random from the range $[l, r]$.

Bessie generates a random labeled tree on $N$ vertices ($2\le N\le 2\cdot 10^5$) using the following two-step process:

1. Start with vertices labeled $1$ through $N$. For each $i$ from $2$ to $N$, add an edge between vertex $i$ and $\text{randint}(1, i-1)$.
2. Choose a permutation $p_1, p_2, \dots, p_N$ of $\{1, 2, \ldots, N\}$ uniformly at random. Relabel every vertex $v$ as $p_v$.

Now, Farmer John is looking at the edge set of the final tree and wants to know the probability that the two-step process above produces a tree with exactly this edge set. Can you determine this probability modulo $10^9 + 7$?

## Input Format

The input consists of $T$ ($1\le T\le 10$) independent inputs. Each input is specified as follows:

The first line contains $N$.

The next $N - 1$ lines contain the edges of the tree specified by two space-separated integers $u$ and $v$ ($1\le u, v\le N$). It is guaranteed that these edges induce a tree.

It is guaranteed that the sum of $N$ across all tests does not exceed $5\cdot 10^5$.

## Output Format

For each test, output the probability modulo $10^9 + 7$ on a new line (note that the output probability is a ratio of integers, so you will want to print the result of this division when working modulo $10^9 + 7$).

## Examples

**Input 1**

```
4
2
2 1
3
1 2
2 3
4
1 2
2 3
2 4
4
1 2
2 3
3 4
```

**Output 1**

```
1
333333336
83333334
55555556
```

## Note

The probabilities are $1$, $1/3$, $1/12$, $1/18$.

- First test: There is only one tree on $N = 2$ vertices, so the probability of generating it is just $1$.
- Second test: there are three trees on $N = 3$ vertices, and each of them is equally likely to have been generated by the process above. And $1/3\equiv 333333336\pmod{10^9 + 7}$.

## Scoring

- Inputs 2-3: $N\le 8$
- Inputs 4-9: $N\le 2000$
- Inputs 10-21: No additional constraints

**Problem credits:** Benjamin Qi

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 10, "T"); inf.readEoln();
    long long sumN = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(2, 200000, "N"); inf.readEoln();
        sumN += N;
        for (int i = 1; i < N; i++) {
            int u = inf.readInt(1, N, "u"); inf.readSpace();
            int v = inf.readInt(1, N, "v"); inf.readEoln();
            ensuref(u != v, "test %d edge %d: self-loop", tc, i);
        }
    }
    ensuref(sumN <= 500000, "sum N %lld > 5e5", sumN);
    inf.readEof(); return 0;
}

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
int main() {
    cin.tie(0)->sync_with_stdio(0);
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        vector<vector<int>> adj(n);
        for (int i = 0; i < n - 1; i++) {
            int u, v;
            cin >> u >> v, u--, v--;
            adj[u].push_back(v);
            adj[v].push_back(u);
        }
        vector<int> inv(n + 1);
        inv[1] = 1;
        for (int i = 2; i <= n; i++)
            inv[i] = (ll)inv[MOD % i] * (MOD - MOD / i) % MOD;
        vector<int> sz(n), dp(n);
        auto dfs = [&](auto dfs, int p, int i) -> void {
            sz[i] = 1;
            dp[i] = 1;
            for (int j : adj[i])
                if (p != j) {
                    dfs(dfs, i, j);
                    sz[i] += sz[j];
                    dp[i] = (ll)dp[i] * dp[j] % MOD;
                }
            dp[i] = (ll)dp[i] * inv[sz[i]] % MOD;
        };
        dfs(dfs, -1, 0);  // dp[0] = inverse product for root
        auto make = [&](auto make, int p, int i) -> void {
            for (int j : adj[i])
                if (p != j) {
                    dp[j] = (ll)dp[i] * sz[j] % MOD * inv[n - sz[j]] % MOD;
                    make(make, i, j);
                }
        };
        make(make, -1, 0);  // get inverse product (dp) for all other verts
        ll ways = 0;
        for (int i = 0; i < n; i++) ways += dp[i];
        ways %= MOD;
        for (int i = 1; i < n; i++)
            ways = ways * inv[i] % MOD;  // divide by (n-1)!
        cout << ways << '\n';
    }
}

verbatim earliest root score=100 submission #70953


All Pairs Shortest Paths

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

You have a bunch of triangular regions that tessellate an infinite 2D plane. The tessellation is defined as follows (see the diagram for a better understanding):

- Recall that Euler's formula states that $e^{ix} = \cos(x) + i\sin(x)$ for real $x$. First, draw a vertex at $x + y\exp(\pi i/3)$ on the complex plane for all integers $x, y$.
- Then for every three vertices from the step above forming an equilateral triangle with side length $1$, draw the edges forming its border. Additionally, draw a vertex at the center of the triangle and edges from the center of the triangle to each of three outer vertices.

You are given $N$ ($2\le N\le 2\cdot 10^5$) input points, each of which lies strictly within some region (i.e., not on any vertex or edge). For any pair of the input points, define the distance between them to be the smallest number of edges crossed when drawing a path from one point to the other that doesn't pass through any vertex.

Output the sum of all $N(N-1)/2$ pairwise distances between the input points.

## Input Format

The first line contains $T$ ($T\ge 1$), the number of independent tests. Each test is specified as follows:

The first line contains $N$.

The next $N$ lines each contain three integers $x$, $y$, and $z$ ($0\le x, y < 10^6$, $0\le z < 12$) representing a point at $x + y\exp(\pi i/3) + \epsilon\cdot \exp((1 + 2z)\pi i/12)$ on the complex plane ($\epsilon$ being a small positive number).

It is guaranteed that the sum of $N$ over all tests doesn't exceed $2\cdot 10^5$.

## Output Format

For each test, output the sum of all $N(N-1)/2$ pairwise distances on a new line.

## Examples

**Input 1**

```
6
2
0 0 0
0 0 0
2
0 0 0
1 1 7
2
0 0 0
0 0 6
3
0 0 1
0 0 5
0 0 9
2
0 2 11
1 1 1
2
2 0 11
1 1 1
```

**Output 1**

```
0
3
6
12
2
6
```

## Note

The second test is illustrated by the following:

- The vertex at $x + y\exp(\pi i/3)$ is labeled with $(x, y)$ for each $x\in [-1, 2]$, $y\in [-1, 2]$.
- Dots are drawn at the vertices mentioned above as well as the vertices that are the centers of each equilateral triangle.
- The triangular region containing $(x, y, z) = (0, 0, 0)$ is highlighted in green.
- The triangular region containing $(x, y, z) = (1, 1, 7)$ is highlighted in blue. Note that $15\pi/12 = 225°$.
- An example path from the first region to the second crossing three edges is drawn.

## Scoring

- Inputs 2-5: $N\le 10$, $0\le x, y < 5$
- Inputs 6-13: $N\le 10$
- Inputs 14-21: $T = 1$

**Problem credits:** Benjamin Qi

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 2000000000, "T"); inf.readEoln();
    long long sumN = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(1, 200000, "N"); inf.readEoln();
        sumN += N;
        for (int i = 1; i <= N; i++) {
            inf.readInt(0, 999999, "x"); inf.readSpace();
            inf.readInt(0, 999999, "y"); inf.readSpace();
            inf.readInt(0, 11, "z"); inf.readEoln();
        }
    }
    ensuref(sumN <= 200000, "sum N %lld > 2e5", sumN);
    inf.readEof(); return 0;
}

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

void solve() {
  int n;
  cin >> n;
  vector<array<int, 3>> p(n);
  for (auto &[x, y, z] : p)
    cin >> x >> y >> z;

  // compute sum of pairwise abs difference given map of counts
  auto calc_dir = [&](map<int, int> &m) {
    ll ret = 0;
    int pos = m.begin()->first;
    int cnt = m.begin()->second;
    m.erase(m.begin());
    for (auto [k, v] : m) {
      ret += ll(k - pos) * cnt * (n - cnt);
      cnt += v;
      pos = k;
    }
    return ret;
  };

  // location in equilateral triangle grid
  // bool denotes inside downward-pointing triangle to the right
  vector<tuple<int, int, bool>> loc;
  // compute sum of pairwise distance in equilateral triangle grid
  auto calc = [&]() {
    ll ret = 0;

    map<int, int> m;
    for (auto [x, y, z] : loc)
      m[x]++;
    ret += calc_dir(m);

    m.clear();
    for (auto [x, y, z] : loc)
      m[y]++;
    ret += calc_dir(m);

    m.clear();
    for (auto [x, y, z] : loc)
      m[x + y + z]++;
    ret += calc_dir(m);

    return ret;
  };

  // equilateral triangle grid
  ll ans = 0;
  for (auto [x, y, z] : p) {
    loc.push_back({
        x - (z > 1 && z < 8),
        y - (z > 5),
        (z % 4) > 1,
    });
  }
  ans += calc();

  // upward hexagon grid
  loc.clear();
  for (auto [x, y, z] : p) {
    loc.push_back({
        x - (z > 2 && z < 7),
        y - (z > 6 && z != 11),
        0,
    });
  }
  ans += calc() / 2;

  // downward hexagon grid
  loc.clear();
  for (auto [x, y, z] : p) {
    loc.push_back({
        x - (z != 0 && z < 9),
        y - (z == 0 || z > 4),
        1,
    });
  }
  ans += calc() / 2;

  // count by rhombi by chain
  map<int, map<int, int>> m1, m2, m3;
  for (auto [x, y, z] : p) {
    int dir = z % 6;
    if (dir == 0 || dir == 5) // horizontal
      m1[y][x - (z == 5 || z == 6)]++;
    else if (dir == 1 || dir == 2) // up-right
      m2[x][y - (z == 7 || z == 8)]++;
    else // up-left
      m3[x + y][y - (z == 9 || z == 10)]++;
  }
  auto chains = [&](map<int, map<int, int>> &m) {
    for (auto [k, v] : m) {
      int total = 0;
      for (auto [k2, v2] : v) {
        total += v2;
        ans -= (ll)v2 * (v2 - 1) / 2;
      }
      ans += (ll)total * (total - 1) / 2;
    }
  };
  chains(m1);
  chains(m2);
  chains(m3);
  cout << ans << '\n';
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int t;
  cin >> t;
  while (t--)
    solve();
}

verbatim earliest root score=100 submission #70948


Blast Damage

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

Bessie is playing a video game where she needs to defeat a line of $N$ enemies with initial HPs given by the list $v_1\dots v_N$ ($1\le N\le 2\cdot 10^5$, $0\le v_i\le 10^9$). In one attack, she can perform the following sequence of steps:

- Choose $i$ such that the $i$-th enemy is still alive (that is, $v_i > 0$).
- Deal one damage to the $i$-th enemy and all enemies adjacent to it that are still alive. Specifically, for each $j\in [\max(i-1, 1), \min(i+1, N)]$, if $v_j > 0$, subtract one from $v_j$.

Help Bessie determine the minimum number of attacks she needs to defeat all enemies (that is, reduce all $v_i$ to $0$).

Additionally, you are given a parameter $M$ ($0\le M\le 2$). If $M > 0$, please output a construction achieving the minimum number of attacks with a small number of *runs*, where a run consists of attacking the same enemy consecutively.

Let $R$ be the number of runs in your construction. Your construction should be in the following format: output $R$ on its own line, followed by $R$ lines each containing two integers $i$ and $r$ ($1\le i\le N$, $0\le r\le 10^9$), meaning that Bessie attacks the $i$-th enemy $r$ times consecutively.

Depending on the value of $M$, $R$ must satisfy one of the following constraints:

- $M = 1$: $R\le 2N$ (it can be proven that a construction always exists).
- $M = 2$: $R\le f(N)$, where $f(N)$ is the maximum minimum number of runs over all lists of length $N$.

## Input Format

Each input consists of $T$ ($1\le T\le 10^5$) independent tests. The first line contains $T$ and $M$.

Each test is specified as follows:

The first line contains $N$.

The second line contains $v_1\dots v_N$.

It is guaranteed that the sum of $N$ over all tests does not exceed $10^6$.

## Output Format

For each test, output the minimum number of attacks on the first line.

Then if $M > 0$, output $R + 1$ additional lines as specified above. Any valid construction will be accepted.

## Examples

**Input 1**

```
2 0
1
10
3
6 1 7
```

**Output 1**

```
10
12
```

**Input 2**

```
2 1
1
10
3
6 1 7
```

**Output 2**

```
10
2
1 0
1 10
12
4
2 1
1 5
3 2
3 4
```

**Input 3**

```
2 2
1
10
3
6 1 7
```

**Output 3**

```
10
1
1 10
12
3
2 1
3 6
1 5
```

## Note

For the second test of the first example, you can first perform one attack on the middle enemy. Then, in any order after that, perform five attacks on the first enemy and six attacks on the last enemy.

The output of the second example receives credit because $R = 2\le 2$ for test $1$ and $R = 4\le 6$ for test $2$.

The output of the third example receives credit because $R = 1\le f(1)$ for test $1$ and $R = 3\le f(3)$ for test $2$.

## Scoring

- Inputs 4-7: $M = 0$
- Inputs 8-11: $M = 1$
- Inputs 12-13: $M = 2$

**Problem credits:** Benjamin Qi

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 100000, "T"); inf.readSpace();
    inf.readInt(0, 2, "M"); inf.readEoln();
    long long sumN = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(1, 200000, "N"); inf.readEoln();
        sumN += N;
        for (int i = 1; i <= N; i++) { inf.readInt(0, 1000000000, "v_i"); if (i < N) inf.readSpace(); }
        inf.readEoln();
    }
    ensuref(sumN <= 1000000, "sum N %lld > 1e6", sumN);
    inf.readEof(); return 0;
}

#include <bits/stdc++.h>
using namespace std;

template <class T> using V = vector<T>;
#define all(x) begin(x), end(x)

using ll = long long;

int M;

pair<ll, vector<pair<int, ll>>> get_ops(const vector<ll> &v) {
    int N = size(v);

    // get op count
    vector<int> a(N);
    for (int i = 0; i < N; ++i) {  // satisfy i-th type 2 constraint by increasing a_{i+1} and a_i
        ll remaining = v.at(i) - a.at(i);
        if (i > 0) remaining -= a.at(i - 1);
        remaining = max(remaining, 0LL);
        if (i + 1 < N) {
            a.at(i + 1) = min(remaining, v.at(i + 1));
            remaining -= a.at(i + 1);
        }
        a.at(i) += remaining;
    }
    ll op_count = accumulate(begin(a), end(a), 0LL);

    // construction
    auto sensitive = [&](int i) {
        assert(0 <= i && i < N);
        return ((i == 0 ? 0 : a.at(i - 1)) + a.at(i) +
                    (i + 1 == N ? 0 : a.at(i + 1)) >
                v.at(i)) &&
               a.at(i);
    };
    vector<pair<int, ll>> runs;
    for (int i = 0; i < N; ++i)
        if (sensitive(i)) {
            if (i) assert(!sensitive(i - 1));
            // sanity check: no two consecutive sensitive indices
            runs.push_back({i, a.at(i)});
        }
    for (int i = 0; i < N; ++i)
        if (!sensitive(i) && a.at(i)) { runs.push_back({i, a.at(i)}); }
    return {op_count, runs};
}

void solve() {
    int N;
    cin >> N;
    vector<ll> v(N);
    for (auto &t : v) cin >> t;
    auto ans = get_ops(v);
    bool rev = false;
    if (N % 2 == 0 && size(ans.second) == N) {  // for M=2
        rev = true;
        reverse(all(v));
        ans = get_ops(v);
        assert(size(ans.second) < N);
    }
    const auto &[op_count, runs] = ans;
    cout << op_count << "\n";
    if (M) {
        cout << size(runs) << "\n";
        for (auto [i, r] : runs)
            cout << (rev ? N - i : i + 1) << " " << r << "\n";
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int T;
    cin >> T >> M;
    while (T--) solve();
}

#include "testlib.h"
#include <vector>
using namespace std;
typedef long long ll;

int main(int argc, char *argv[]) {
    setName("USACO 2026 Platinum: Blast Damage");
    registerTestlibCmd(argc, argv);

    int T = inf.readInt();
    int M = inf.readInt();

    for (int t = 1; t <= T; t++) {
        int N = inf.readInt();
        vector<ll> v(N + 2, 0);
        for (int i = 1; i <= N; i++) v[i] = inf.readLong();

        ll cnt_ref = ans.readLong();
        ll cnt = ouf.readLong();
        if (cnt != cnt_ref)
            quitf(_wa, "test %d: minimum attack count differs (expected %lld, got %lld)",
                  t, cnt_ref, cnt);

        if (M > 0) {
            // Read reference's R + R lines (consume only)
            int R_ref = ans.readInt();
            for (int j = 0; j < R_ref; j++) { ans.readInt(); ans.readLong(); }

            int R = ouf.readInt(0, (int)2e9, "R");

            // Bound check
            if (M == 1) {
                if (R > 2 * N)
                    quitf(_wa, "test %d: R=%d exceeds 2N=%d (M=1)", t, R, 2 * N);
            } else { // M == 2
                // f(N) = max over all length-N lists of the minimum number of
                // runs = N if N is odd, else N-1 (see editorial). R_ref (the
                // reference's run count on THIS list) is only a lower bound on
                // f(N), so bounding by R_ref would wrongly reject valid
                // constructions that use up to f(N) runs.
                int fN = (N % 2 == 1) ? N : N - 1;
                if (R > fN)
                    quitf(_wa, "test %d: R=%d exceeds f(N)=%d (M=2)",
                          t, R, fN);
            }

            ll total_r = 0;
            for (int j = 0; j < R; j++) {
                int idx = ouf.readInt(1, N, "i");
                ll r = ouf.readLong();
                if (r < 0 || r > (ll)1e9)
                    quitf(_wa, "test %d: run #%d r=%lld out of [0, 1e9]", t, j + 1, r);
                if (r == 0) continue;
                if (v[idx] <= 0)
                    quitf(_wa, "test %d: run #%d attacks dead enemy %d", t, j + 1, idx);
                if (r > v[idx])
                    quitf(_wa, "test %d: run #%d r=%lld exceeds v[%d]=%lld (would attack dead)",
                          t, j + 1, r, idx, v[idx]);
                ll a = (idx > 1) ? v[idx - 1] : 0;
                ll c = (idx < N) ? v[idx + 1] : 0;
                v[idx] -= r;
                if (idx > 1) v[idx - 1] = max((ll)0, a - r);
                if (idx < N) v[idx + 1] = max((ll)0, c - r);
                total_r += r;
            }

            if (total_r != cnt)
                quitf(_wa, "test %d: sum of run lengths = %lld != minimum attacks = %lld",
                      t, total_r, cnt);

            for (int i = 1; i <= N; i++)
                if (v[i] != 0)
                    quitf(_wa, "test %d: enemy %d still has HP %lld after construction",
                          t, i, v[i]);
        }
    }

    if (!ouf.seekEof())
        quitf(_wa, "extra tokens in contestant output");
    quitf(_ok, "T=%d cases, M=%d", T, M);
}

verbatim earliest root score=100 submission #70949


Min Max Subarrays II

**Time limit:** 2 seconds    **Memory limit:** 256 megabytes

## Description

You are given integers $N, Q$ ($1\le N, Q\le 2\cdot 10^5$) and $Q$ constraints represented by four integers $t_i, l_i, r_i, k_i$ ($1\le t_i\le 2$, $1\le l_i\le r_i\le N$, $0\le k_i\le 10^9$, all $k_i$ are distinct).

Construct an array $a$ consisting of $N$ integers between $0$ and $10^9$ such that for all $1\le i\le Q$, $\min a[l_i\ldots r_i] = k_i$ if $t_i = 1$ and $\max a[l_i\ldots r_i] = k_i$ if $t_i = 2$. If multiple valid arrays exist, print any. If no valid array exists, print $-1$.

## Input Format

The first line contains an integer $T$ ($1\le T\le 10^4$) representing the number of independent test cases.

For each test case, the first line contains two integers $N, Q$.

The next $Q$ lines each contain $4$ integers $t_i$ $l_i$ $r_i$ $k_i$.

It is guaranteed that neither the sum of $N$ nor the sum of $Q$ over all test cases exceed $2\cdot 10^5$.

## Output Format

For each test case, if a valid array exists, output $N$ space-separated integers $a_1\dots a_N$ on a new line. Otherwise, print $-1$.

## Examples

**Input 1**

```
3
2 2
1 1 2 1
1 1 2 2
2 2
1 1 2 1
1 2 2 2
4 1
2 2 4 3
```

**Output 1**

```
-1
1 2
0 3 0 0
```

**Input 2**

```
4
2 2
1 1 2 1
2 1 2 2
3 2
1 1 2 3
2 2 3 1
5 2
1 1 2 3
1 4 5 2
4 4
1 1 4 1
1 2 3 2
2 1 2 5
2 3 4 6
```

**Output 2**

```
1 2
-1
3 3 0 2 2
1 5 2 6
```

## Note

For the first example: in the first test case, the answer is $-1$ because the minimum value of the array cannot be both $1$ and $2$ at the same time. In the second test case, $a[1\ldots 2]$ has a minimum of $1$ at $a[1]$ in the sample output, satisfying the first constraint. Since $a[2] = 2$, the second constraint is also satisfied. In the third test case, there are multiple solutions. For instance, the array $[4, 3, 2, 1]$ would also be accepted.

For the second example: in the second test case, the array $[3, 5, 1]$ satisfies the first constraint but not the second constraint. Contrarily, the array $[3, 1, 1]$ satisfies the second constraint but not the first constraint. It can be proven that no array can satisfy both constraints at the same time, hence the answer is $-1$. For all other test cases, it can be proven that the constructed array satisfies all $Q$ constraints.

## Scoring

- Inputs 3-4: $N, Q\le 100$ and all $t_i$ within the same test case are equal
- Inputs 5-6: All $t_i$ within the same test case are equal
- Inputs 7-10: $N, Q\le 100$
- Inputs 11-14: No additional constraints

**Problem credits:** Charlie Yang

#include "testlib.h"
#include <set>
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 10000, "T"); inf.readEoln();
    long long sumN = 0, sumQ = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(1, 200000, "N"); inf.readSpace();
        int Q = inf.readInt(1, 200000, "Q"); inf.readEoln();
        sumN += N; sumQ += Q;
        std::set<int> ks;
        for (int i = 1; i <= Q; i++) {
            inf.readInt(1, 2, "t"); inf.readSpace();
            int l = inf.readInt(1, N, "l"); inf.readSpace();
            int r = inf.readInt(l, N, "r"); inf.readSpace();
            int k = inf.readInt(0, 1000000000, "k"); inf.readEoln();
            ensuref(ks.insert(k).second, "test %d: k value %d repeats (all k distinct)", tc, k);
        }
    }
    ensuref(sumN <= 200000, "sum N %lld > 2e5", sumN);
    ensuref(sumQ <= 200000, "sum Q %lld > 2e5", sumQ);
    inf.readEof(); return 0;
}

#include <algorithm>
#include <iostream>
#include <vector>
#include <set>

using namespace std;

const int N = 200000;
const int M = 200000;

int tt[M], rr[M], aa[M];
vector<int> hh[N];
set<pair<int, int>> qul, qur;
vector<int> ei[M];
int hhl[N], hhr[N], bb[N];
int visited[M], i_;

void dfs(int p, int h) {
	if (visited[h]) {
		i_ = p;
		return;
	}
	visited[h] = 1;
	for (int i : ei[h])
		if (i != p)
			dfs(i, h ^ hhl[i] ^ hhr[i]);
}

void dfs_(int h) {
	if (visited[h] == 2)
		return;
	visited[h] = 2;
	for (int i : ei[h])
		if (bb[i] == -1) {
			int g = h ^ hhl[i] ^ hhr[i];
			bb[i] = aa[g];
			dfs_(g);
		}
}

int main() {
	ios_base::sync_with_stdio(false), cin.tie(NULL);
	int tc; cin >> tc;
	while (tc--) {
		int n, m; cin >> n >> m;
		for (int i = 0; i < n; i++)
			hh[i].clear();
		for (int h = 0; h < m; h++) {
			int t, l, r, a; cin >> t >> l >> r >> a, l--;
			tt[h] = t, rr[h] = r, aa[h] = a;
			hh[l].push_back(h << 1 ^ 0);
			if (r < n)
				hh[r].push_back(h << 1 ^ 1);
		}
		bool yes = true;
		qul.clear(), qur.clear();
		for (int h = 0; h < m; h++)
			ei[h].clear();
		for (int i = 0; i < n; i++) {
			for (int h_ : hh[i]) {
				int h = h_ >> 1;
				if (!(h_ & 1)) {
					if (tt[h] == 1)
						qul.insert({ aa[h], h });
					else
						qur.insert({ aa[h], h });
				} else {
					if (tt[h] == 1)
						qul.erase({ aa[h], h });
					else
						qur.erase({ aa[h], h });
				}
			}
			int hl = qul.empty() ? -1 : (*prev(qul.end())).second;
			int hr = qur.empty() ? -1 : (*qur.begin()).second;
			bb[i] = -1;
			if (hl != -1 && hr != -1) {
				if (aa[hl] > aa[hr]) {
					yes = false;
					break;
				}
				ei[hhl[i] = hl].push_back(i);
				ei[hhr[i] = hr].push_back(i);
			} else if (hl != -1) {
				ei[hhl[i] = hl].push_back(i);
				ei[hhr[i] = hl].push_back(i);
			} else if (hr != -1) {
				ei[hhl[i] = hr].push_back(i);
				ei[hhr[i] = hr].push_back(i);
			}
		}
		if (!yes) {
			cout << "-1\n";
			continue;
		}
		for (int h = 0; h < m; h++)
			visited[h] = 0;
		for (int h_ = 0; h_ < m; h_++)
			if (!visited[h_]) {
				i_ = -1, dfs(-1, h_);
				if (i_ == -1) {
					yes = false;
					break;
				}
				int hl = hhl[i_];
				bb[i_] = aa[hl];
				dfs_(hl);
			}
		if (!yes) {
			cout << "-1\n";
			continue;
		}
		for (int i = 0; i < n; i++)
			cout << (bb[i] != -1 ? bb[i] : 0) << " \n"[i + 1 == n];
	}
	return 0;
}

#include "testlib.h"
#include <vector>
using namespace std;
typedef long long ll;

int main(int argc, char *argv[]) {
    setName("USACO 2026 Platinum: Min Max Subarrays II");
    registerTestlibCmd(argc, argv);

    int T = inf.readInt();
    for (int t = 1; t <= T; t++) {
        int N = inf.readInt();
        int Q = inf.readInt();
        vector<int> tt(Q), ll_(Q), rr(Q);
        vector<ll> kk(Q);
        for (int i = 0; i < Q; i++) {
            tt[i] = inf.readInt();
            ll_[i] = inf.readInt();
            rr[i] = inf.readInt();
            kk[i] = inf.readLong();
        }

        // Reference output: -1 or N integers.
        // Use the first token to detect.
        string firstAns = ans.readToken();
        bool refImpossible = (firstAns == "-1");
        if (!refImpossible) {
            // already consumed first integer; consume remaining N-1
            for (int i = 1; i < N; i++) ans.readLong();
        }

        string firstOuf = ouf.readToken();
        if (firstOuf == "-1") {
            if (!refImpossible)
                quitf(_wa, "test %d: contestant says impossible but reference shows feasible", t);
            continue;
        }

        if (refImpossible)
            quitf(_wa, "test %d: contestant claims feasible but reference says impossible", t);

        // Parse contestant's N values: firstOuf is the first integer.
        vector<ll> a(N);
        try {
            a[0] = stoll(firstOuf);
        } catch (...) {
            quitf(_wa, "test %d: first token '%s' is not an integer", t, firstOuf.c_str());
        }
        for (int i = 1; i < N; i++) a[i] = ouf.readLong();

        for (int i = 0; i < N; i++)
            if (a[i] < 0 || a[i] > (ll)1e9)
                quitf(_wa, "test %d: a[%d]=%lld out of [0, 1e9]", t, i + 1, a[i]);

        // Build sparse tables for min and max for O(1) range query.
        int LOG = 1;
        while ((1 << LOG) <= N) LOG++;
        vector<vector<ll>> mn(LOG, vector<ll>(N)), mx(LOG, vector<ll>(N));
        for (int i = 0; i < N; i++) mn[0][i] = mx[0][i] = a[i];
        for (int k = 1; k < LOG; k++) {
            int len = 1 << k;
            for (int i = 0; i + len <= N; i++) {
                mn[k][i] = min(mn[k - 1][i], mn[k - 1][i + (len >> 1)]);
                mx[k][i] = max(mx[k - 1][i], mx[k - 1][i + (len >> 1)]);
            }
        }
        auto qmin = [&](int l, int r) {
            int k = __lg(r - l + 1);
            return min(mn[k][l], mn[k][r - (1 << k) + 1]);
        };
        auto qmax = [&](int l, int r) {
            int k = __lg(r - l + 1);
            return max(mx[k][l], mx[k][r - (1 << k) + 1]);
        };

        for (int i = 0; i < Q; i++) {
            ll val = (tt[i] == 1) ? qmin(ll_[i] - 1, rr[i] - 1) : qmax(ll_[i] - 1, rr[i] - 1);
            if (val != kk[i])
                quitf(_wa, "test %d: constraint %d (t=%d l=%d r=%d k=%lld) violated; computed value=%lld",
                      t, i + 1, tt[i], ll_[i], rr[i], kk[i], val);
        }
    }

    if (!ouf.seekEof())
        quitf(_wa, "extra tokens in contestant output");
    quitf(_ok, "T=%d cases", T);
}

verbatim earliest root score=100 submission #70983