Chip Exchange

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

## Description

Bessie the cow has in her possession $A$ chips of type A and $B$ chips of type B ($0\le A, B\le 10^9$). She can perform the following operation as many times as she likes:

> If you have at least $c_B$ chips of type B, exchange $c_B$ chips of type B for $c_A$ chips of type A ($1\le c_A, c_B\le 10^9$).

Determine the minimum non-negative integer $x$ such that the following holds: after receiving $x$ additional random chips, it is guaranteed that Bessie can end up with at least $f_A$ chips of type A ($0\le f_A\le 10^9$).

## Input Format

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

Then follow $T$ tests, each consisting of five integers $A, B, c_A, c_B, f_A$.

## Output Format

Output the answer for each test on a separate line.

**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**

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

**Output 1**

```
1
0
```

**Input 2**

```
5
0 0 2 3 5
0 1 2 3 5
1 0 2 3 5
10 10 2 3 5
0 0 1 1000000000 1000000000
```

**Output 2**

```
9
8
7
0
1000000000000000000
```

## Note

For the first test of the second example, Bessie initially starts with no chips. If she receives any $9$ additional chips, she can perform the operation to end up with at least $5$ chips of type A. For example, if she receives $2$ chips of type A and $7$ chips of type B, she can perform the operation twice to end up with $6\ge 5$ chips of type A. However, if she only receives $8$ chips of type B, she can only end up with $4 < 5$ chips of type A.

For the fourth test of the second example, she already has enough chips of type A from the start.

## Scoring

- Input 3: $c_A = c_B = 1$
- Inputs 4-5: $x\le 10$ for all cases
- Inputs 6-7: $c_A = 2$, $c_B = 3$
- Inputs 8-12: No additional constraints

**Problem credits:** Benjamin Qi

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 10000, "T");
    inf.readEoln();
    for (int tc = 1; tc <= T; tc++) {
        inf.readInt(0, 1000000000, "A"); inf.readSpace();
        inf.readInt(0, 1000000000, "B"); inf.readSpace();
        inf.readInt(1, 1000000000, "c_A"); inf.readSpace();
        inf.readInt(1, 1000000000, "c_B"); inf.readSpace();
        inf.readInt(0, 1000000000, "f_A");
        inf.readEoln();
    }
    inf.readEof();
    return 0;
}

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

ll solve(ll A, ll B, ll cA, ll cB, ll fA) {
    ll init = B / cB * cA + A;
    if (init >= fA) return 0;
    ll nA0 = fA - 1 - init;
    ll y = cB - 1 - B % cB;
    if (cA >= cB) y += nA0;
    else y += nA0 / cA * cB + nA0 % cA;
    return y + 1;
}

int main() {
    int T;
    scanf("%d", &T);
    while (T--) {
        ll A, B, cA, cB, fA;
        scanf("%lld %lld %lld %lld %lld", &A, &B, &cA, &cB, &fA);
        printf("%lld\n", solve(A, B, cA, cB, fA));
    }
    return 0;
}

hand C++ translation (earliest root AC #70933 was Python3)


COW Splits

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

## Description

Bessie is given a positive integer $N$ and a string $S$ of length $3N$ which is generated by concatenating $N$ strings of length $3$, each of which is a cyclic shift of "COW". In other words, each string will be "COW", "OWC", or "WCO".

String $X$ is a *square string* if and only if there exists a string $Y$ such that $X = Y + Y$ where $+$ represents string concatenation. For example, "COWCOW" and "CC" are examples of square strings but "COWO" and "OC" are not.

In a single operation, Bessie can remove any *subsequence* $T$ from $S$ where $T$ is a square string. A subsequence of a string is a string which can be obtained by removing several (possibly zero) characters from the original string.

Your job is to help Bessie determine whether it is possible to transform $S$ into an empty string. Additionally, if it is possible, then you must provide a way to do so.

Bessie is also given a parameter $k$ which is either $0$ or $1$. Let $M$ be the number of operations in your construction.

- If $k = 0$, then $M$ must equal the minimum possible number of operations.
- If $k = 1$, then $M$ can be up to one plus the minimum possible number of operations.

## Input Format

The first line contains $T$, the number of independent test cases ($1\le T\le 10^4$) and $k$ ($0\le k\le 1$).

The first line of each test case has $N$ ($1\le N\le 10^5$).

The second line of each test case has $S$.

The sum of $N$ across all test cases will not exceed $10^5$.

## Output Format

For each test case, output either one or two lines using the following procedure.

If it is impossible to transform $S$ into an empty string, print $-1$ on a single line.

Otherwise, on the first line print $M$ — the number of operations in your construction. On the second line, print $3N$ space-separated integers. The $i$-th integer $x$ indicates that the $i$-th letter of $S$ was deleted as part of the $x$-th subsequence ($1\le x\le M$).

## Examples

**Input 1**

```
3 1
3
COWOWCWCO
4
WCOCOWWCOCOW
6
COWCOWOWCOWCOWCOWC
```

**Output 1**

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

**Input 2**

```
3 0
3
COWOWCWCO
4
WCOCOWWCOCOW
6
COWCOWOWCOWCOWCOWC
```

**Output 2**

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

## Note

For the last test of the first example, the optimal number of operations is two, so any valid construction with either $M = 2$ or $M = 3$ would be accepted.

For $M = 3$, here is a possible construction:

- In the first operation, remove the last twelve characters. Now we're left with `COWCOW`.
- In the second operation, remove the subsequence `WW`. Now we're left with `COCO`.
- In the last operation, remove all remaining characters.

## Scoring

- Inputs 3-4: $T\le 10$, $N\le 6$, $k = 0$
- Inputs 5-6: $k = 1$
- Inputs 7-14: $k = 0$

**Problem credits:** Aakash Gokhale

#include "testlib.h"
#include <string>
static bool isCyclicCOW(const std::string& g) {
    return g == "COW" || g == "OWC" || g == "WCO";
}
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 10000, "T");
    inf.readSpace();
    inf.readInt(0, 1, "k");
    inf.readEoln();
    long long sumN = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(1, 100000, "N");
        inf.readEoln();
        sumN += N;
        std::string s = inf.readLine();
        ensuref((int)s.size() == 3 * N,
                "test %d: |S|=%d, expected 3N=%d", tc, (int)s.size(), 3 * N);
        for (int i = 0; i < N; i++) {
            std::string g = s.substr(3 * i, 3);
            ensuref(isCyclicCOW(g),
                    "test %d: group %d '%s' is not a cyclic shift of COW", tc, i + 1, g.c_str());
        }
    }
    ensuref(sumN <= 100000, "sum N is %lld > 100000", sumN);
    inf.readEof();
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(0); cin.tie(0);
  int t, x; cin >> t >> x;
  while (t--) {
    int n; cin >> n;
    string s; cin >> s;
    if (n & 1) {
      cout << -1 << endl;
      continue;
    }
    vector<int> ans(n * 3, 1);
    for (int i = 0; i < n / 2; i++) {
      string l = s.substr(i * 3, 3);
      string r = s.substr((i + n / 2) * 3, 3);
      if (l != r) {
        if (l.substr(0, 2) == r.substr(1, 2)) {
          ans[i * 3 + 2] = 2;
          ans[(i + n / 2) * 3] = 2;
        } else if (l.substr(1, 2) == r.substr(0, 2)) {
          ans[i * 3] = 2;
          ans[(i + n / 2) * 3 + 2] = 2;
        }
      }
    }
    cout << *max_element(ans.begin(), ans.end()) << endl;
    for (int i = 0; i < n * 3; i++) {
      cout << ans[i] << " \n"[i == 3 * n - 1];
    }
  }
}

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

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

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

    for (int t = 1; t <= T; t++) {
        int N = inf.readInt();
        string S = inf.readToken();
        if ((int)S.size() != 3 * N)
            quitf(_fail, "judge input malformed at test %d", t);

        // Read reference's M_ref (or -1 if impossible)
        int M_ref = ans.readInt();
        if (M_ref >= 1) {
            // consume the reference's 3N integers
            for (int i = 0; i < 3 * N; i++) ans.readInt();
        }

        // Read contestant's first integer: M, or -1
        int M = ouf.readInt();

        if (M_ref == -1) {
            if (M != -1)
                quitf(_wa, "test %d: expected -1 (impossible), got M=%d", t, M);
            continue;
        }

        // M_ref >= 1, so problem is solvable.
        if (M == -1)
            quitf(_wa, "test %d: contestant claims impossible but reference shows M=%d feasible",
                  t, M_ref);

        if (M < 1)
            quitf(_wa, "test %d: M must be >= 1, got %d", t, M);

        // M bounds. The reference output always uses the exact minimum number
        // of operations, so M_ref == true minimum.
        // - K=0: M must equal the minimum, i.e. M == M_ref (M < M_ref is
        //   impossible by definition of minimum).
        // - K=1: M may be up to minimum + 1, i.e. M <= M_ref + 1.
        int M_max = (K == 0) ? M_ref : (M_ref + 1);
        if (M > M_max)
            quitf(_wa, "test %d: M=%d exceeds allowed max %d (M_ref=%d, K=%d)",
                  t, M, M_max, M_ref, K);

        // Read contestant's 3N assignments
        vector<int> a(3 * N);
        for (int i = 0; i < 3 * N; i++) a[i] = ouf.readInt(1, M, "a_i");

        // For each subsequence index s in [1..M], collect characters in order; verify square.
        for (int s = 1; s <= M; s++) {
            string sub;
            for (int i = 0; i < 3 * N; i++)
                if (a[i] == s) sub += S[i];
            int len = sub.size();
            if (len == 0)
                quitf(_wa, "test %d: subsequence %d is empty", t, s);
            if (len & 1)
                quitf(_wa, "test %d: subsequence %d has odd length %d", t, s, len);
            int half = len / 2;
            if (sub.substr(0, half) != sub.substr(half))
                quitf(_wa, "test %d: subsequence %d is not a square string: '%s'",
                      t, s, sub.c_str());
        }
    }

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

verbatim earliest root score=100 submission #70934


Photoshoot

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

## Description

Farmer John is looking at his cows in a magical field and wants to take pictures of subsets of his cows.

The field can be seen as a $N\times N$ grid ($1\le N\le 500$), with a single stationary cow at each location. Farmer John's camera is capable of taking a picture of any $K\times K$ square that is part of the field ($1\le K\le \min(N, 25)$).

At all times, each cow has a beauty value between $0$ and $10^6$. The *attractiveness index* of a picture is the sum of the beauty values of the cows contained in the picture.

The beauty value for every cow starts out as $0$, so the attractiveness index of any picture in the beginning is $0$.

At $Q$ times ($1\le Q\le 3\cdot 10^4$), the beauty of a single cow will increase by a positive integer due to eating the magical grass that is planted on Farmer John's field.

Farmer John wants to know the maximum attractiveness index of a picture he can take after each of the $Q$ updates.

## Input Format

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

The following line contains an integer $Q$.

Each of the following $Q$ lines contains three integers: $r$, $c$, and $v$, which are the row, column, and new beauty value, respectively ($1\le r, c\le N$, $1\le v\le 10^6$). It is guaranteed that the new beauty value is greater than the beauty value at that location before.

## Output Format

Output $Q$ lines, corresponding to the maximum attractiveness index of a picture after each update.

## Examples

**Input 1**

```
4 2
3
2 2 11
3 4 3
3 1 100
```

**Output 1**

```
11
11
111
```

**Input 2**

```
3 1
3
2 2 3
2 2 5
2 2 7
```

**Output 2**

```
3
5
7
```

## Note

For the first example: after the first update, a picture with the maximum attractiveness index is the picture with upper-left corner $(2, 2)$ and lower-right corner $(3, 3)$, which has an attractiveness index of $11 + 0 + 0 + 0 = 11$. The second update does not affect the maximum attractiveness index. After the third update, the picture with the maximum attractiveness index changes to the picture with upper-left corner $(2, 1)$ and lower-right corner $(3, 2)$, which has an attractiveness index of $0 + 11 + 100 + 0 = 111$.

For the second example, there is only one cow with a positive beauty value, so the maximum attractiveness index will always include that cow.

## Scoring

- Inputs 3-6: $N\le 50$, $Q\le 100$
- Inputs 7-10: $N\le 50$
- Inputs 11-18: No additional constraints

**Problem credits:** Brian Law and Cici Liu

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int N = inf.readInt(1, 500, "N");
    inf.readSpace();
    int K = inf.readInt(1, std::min(N, 25), "K");
    inf.readEoln();
    int Q = inf.readInt(1, 30000, "Q");
    inf.readEoln();
    for (int i = 1; i <= Q; i++) {
        inf.readInt(1, N, "r"); inf.readSpace();
        inf.readInt(1, N, "c"); inf.readSpace();
        inf.readInt(1, 1000000, "v");
        inf.readEoln();
    }
    inf.readEof();
    return 0;
}

#include <algorithm>
#include <ios>
#include <iostream>
#include <vector>

using namespace std;

void solve() {

    int k;
    int n;
    int q;

    cin >> n >> k >> q;

    int mx_sum = 0;
    vector sums(n, vector<int>(n));
    vector vals(n, vector<int>(n));

    for (int i = 0; i < q; ++i) {
        int c;
        int r;
        int v;
        cin >> r >> c >> v;
        --r;
        --c;
        const int diff = v - vals[r][c];
        vals[r][c] = v;
        for (int j = max(r - k + 1, 0); j <= min(r, n - k); ++j) {
            for (int l = max(c - k + 1, 0); l <= min(c, n - k); ++l) {
                sums[j][l] += diff;
                mx_sum = max(mx_sum, sums[j][l]);
            }
        }
        cout << mx_sum << '\n';
    }

}

int main() {

    cin.tie(nullptr);

    ios_base::sync_with_stdio(false);

    solve();

    return 0;

}

verbatim earliest root score=100 submission #70935


Lineup Queries

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

## Description

There is a line of cows, initially (i.e. at time $t = 0$) containing only cow $0$ at position $0$ (here, a cow is at position $k$ if there are $k$ cows in front of it). At time $t$ for $t = 1, 2, 3, \dots$, the cow at position $0$ moves to position $\lfloor t/2\rfloor$, every cow in positions $1 \dots \lfloor t/2\rfloor$ moves forward one position, and cow $t$ joins the line at the end of the line (position $t$).

Answer $Q$ ($1\le Q\le 10^5$) independent queries, each of one of the following types:

1. At what position is cow $c$ immediately after time $t$ ($0\le c\le t\le 10^{18}$)?
2. Which cow is at position $x$ immediately after time $t$ ($0\le x\le t\le 10^{18}$)?

## Input Format

The first line contains $Q$, the number of queries.

The next $Q$ lines each contain three integers specifying a query either of the form "$1\ c\ t$" or "$2\ x\ t$."

## Output Format

Output the answer to each query on a separate line.

## Examples

**Input 1**

```
2
1 4 9
2 2 9
```

**Output 1**

```
2
4
```

**Input 2**

```
22
1 0 9
1 1 9
1 2 9
1 3 9
1 4 9
1 5 9
1 6 9
1 7 9
1 8 9
1 9 9
2 0 9
2 1 9
2 2 9
2 3 9
2 4 9
2 5 9
2 6 9
2 7 9
2 8 9
2 9 9
1 0 1000000000000000000
2 0 1000000000000000000
```

**Output 2**

```
1
3
0
4
2
5
6
7
8
9
2
0
4
1
3
5
6
7
8
9
483992463350322770
148148148148148148
```

## Note

Lineups immediately after various times:

```
t = 0 | 0
t = 1 | 0 1
t = 2 | 1 0 2
t = 3 | 0 1 2 3
t = 4 | 1 2 0 3 4
t = 5 | 2 0 1 3 4 5
t = 6 | 0 1 3 2 4 5 6
t = 7 | 1 3 2 0 4 5 6 7
t = 8 | 3 2 0 4 1 5 6 7 8
t = 9 | 2 0 4 1 3 5 6 7 8 9
```

Immediately after $t = 9$, the location of cow $4$ is $2$, and the cow located at position $2$ is $4$.

## Scoring

- Input 3: $Q\le 1000$, $t\le 100$
- Input 4: $t\le 5000$
- Inputs 5-8: All queries are of type 1
- Inputs 9-12: All queries are of type 2

**Problem credits:** Agastya Goel

#include "testlib.h"
const long long MAXT = 1000000000000000000LL;
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int Q = inf.readInt(1, 100000, "Q");
    inf.readEoln();
    for (int q = 1; q <= Q; q++) {
        int type = inf.readInt(1, 2, "type");
        inf.readSpace();
        long long a = inf.readLong(0, MAXT, "arg"); // c or x
        inf.readSpace();
        long long t = inf.readLong(0, MAXT, "t");
        inf.readEoln();
        ensuref(a <= t, "query %d: need arg <= t (%lld > %lld)", q, a, t);
    }
    inf.readEof();
    return 0;
}

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

// which cow is at position, given time (iterative to avoid deep recursion)
ll get_pos(ll i, ll t) {
    if (t < 2 * i) return i;
    ll cur_t = 2 * i - 1;
    t -= cur_t;
    ll pos = i;
    while (t >= 0) {
        if (t <= pos) return pos - t;
        cur_t += pos;
        t -= pos;
        pos = 0;
        cur_t += 1;
        t -= 1;
        pos = cur_t / 2;
    }
    return pos;
}

// position of cow p at time t (iterative form of the recursion)
ll at_pos(ll p, ll t) {
    while (true) {
        if (t == 0) return p;
        if (p < t / 2) {
            ll step = max((ll)1, (t - 2 * p) / 3);
            p += step;
            t -= step;
        } else if (p == t / 2) {
            p = 0;
            t = t - 1;
        } else {
            return p;
        }
    }
}

int main() {
    int q;
    scanf("%d", &q);
    while (q--) {
        ll a, b, c;
        scanf("%lld %lld %lld", &a, &b, &c);
        if (a == 1) printf("%lld\n", get_pos(b, c));
        else printf("%lld\n", at_pos(b, c));
    }
    return 0;
}

hand C++ translation (earliest root AC #70930 was Python3)


Mooclear Reactor

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

## Description

Bessie is designing a nuclear reactor to power Farmer John's lucrative new AI data center business, CowWeave!

The reactor core consists of $N$ ($1\le N\le 2\cdot 10^5$) fuel rods, numbered $1$ through $N$. The $i$-th rod has a "stable operating range" $[l_i, r_i]$ ($-10^9\le l_i\le r_i\le 10^9$), meaning it can only generate power if its energy $a_i$ (chosen by Bessie) satisfies $l_i\le a_i\le r_i$; otherwise, it sits idle and does not generate power. Moreover, $a_i$ must always be an integer. Note that $a_i$ can be any integer, not limited to $[-10^9, 10^9]$.

However, quantum interactions between the rods mean that there are $M$ constraints of the form $(x, y, z)$ where Bessie must satisfy $a_x + a_y = z$ ($1\le x, y\le N$ and $-10^9\le z\le 10^9$) to prevent the reactor from melting down.

Help Bessie find the maximum number of power-generating rods she can achieve in her design without it melting down!

## 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 the two integers $N$ and $M$.
- The second line contains the $N$ integers $l_1, \dots, l_N$.
- The third line contains the $N$ integers $r_1, \dots, r_N$.
- The next $M$ lines each contain three integers $x$, $y$, and $z$, each representing a constraint.

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

## Output Format

If no choice of rod energies exists that satisfies all constraints, output $-1$. Otherwise, output the maximum number of power-generating rods Bessie can achieve.

## Examples

**Input 1**

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

**Output 1**

```
-1
2
```

**Input 2**

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

**Output 2**

```
3
```

**Input 3**

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

**Output 3**

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

## Note

In the second test of the first example, the constraints require that:

- $a_1 + a_1 = 2$
- $a_2 + a_2 = 10$

Choosing energies $a = [1, 5, 3]$ results in $2$ power-generating rods because:

- $l_1 = 1\le a_1\le 1 = r_1$
- $l_3 = 3\le a_3\le 3 = r_3$

and $a$ satisfies all required constraints.

In the second example, choosing rod energies $a = [10, -10, 10]$ results in $3$ power-generating rods.

## Scoring

- Input 4: $x = y$ for all constraints
- Inputs 5-7: $|x - y| = 1$ for all constraints
- Inputs 8-10: $|x - y|\le 1$ for all constraints
- Inputs 11-13: No additional conditions

**Problem credits:** Akshaj Arora

#include "testlib.h"
#include <vector>
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 400000, "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(0, 400000, "M");
        inf.readEoln();
        sumN += N; sumM += M;
        std::vector<int> l(N + 1);
        for (int i = 1; i <= N; i++) {
            l[i] = inf.readInt(-1000000000, 1000000000, "l_i");
            if (i < N) inf.readSpace();
        }
        inf.readEoln();
        for (int i = 1; i <= N; i++) {
            int r = inf.readInt(-1000000000, 1000000000, "r_i");
            ensuref(r >= l[i], "test %d rod %d: need l<=r (%d > %d)", tc, i, l[i], r);
            if (i < N) inf.readSpace();
        }
        inf.readEoln();
        for (int j = 1; j <= M; j++) {
            inf.readInt(1, N, "x");
            inf.readSpace();
            inf.readInt(1, N, "y");
            inf.readSpace();
            inf.readInt(-1000000000, 1000000000, "z");
            inf.readEoln();
        }
    }
    ensuref(sumN <= 400000, "sum N is %lld > 400000", sumN);
    ensuref(sumM <= 400000, "sum M is %lld > 400000", sumM);
    inf.readEof();
    return 0;
}

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

typedef long long ll;

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

    vector<int> l(n), r(n);
    for (int &i : l) cin >> i;
    for (int &i : r) cin >> i;

    vector<vector<pair<int, int>>> adj(n);
    while (m--) {
        int i, j, x;
        cin >> i >> j >> x, i--, j--;
        adj[i].push_back({j, x});
        adj[j].push_back({i, x});
    }

    bool imp = false;
    auto no = [&]() { imp = true; };

    vector<bool> done(n);
    vector<pair<int, ll>> set_v(n);
    int ans = 0;

    for (int i = 0; i < n; i++)
        if (!done[i]) {
            bool has_set = false;
            ll set_x;
            vector<pair<ll, int>> mod;

            auto dfs = [&](auto self, int i, pair<int, ll> v) -> void {
                if (done[i]) {
                    if (set_v[i].first == v.first) {
                        if (set_v[i].second != v.second) no();
                    } else {
                        ll x = set_v[i].first * set_v[i].second +
                               v.first * v.second;
                        x *= -1;
                        if (x & 1) no();
                        else {
                            x /= 2;
                            if (!has_set) has_set = true, set_x = x;
                            else if (x != set_x) no();
                        }
                    }
                } else {
                    if (v.first == 1) {
                        mod.push_back({l[i] - v.second, 1});
                        mod.push_back({1 + r[i] - v.second, -1});
                    } else {
                        mod.push_back({v.second - r[i], 1});
                        mod.push_back({1 + v.second - l[i], -1});
                    }
                    done[i] = true;
                    set_v[i] = v;
                    for (auto [j, x] : adj[i])
                        self(self, j, {-v.first, x - v.second});
                }
            };
            dfs(dfs, i, {1, 0});

            if (has_set) {
                for (auto [x, y] : mod)
                    if (x <= set_x) ans += y;
            } else {
                sort(mod.begin(), mod.end());
                int cur = 0, opt = 0;
                for (auto [x, y] : mod) opt = max(opt, cur += y);
                ans += opt;
            }
        }
    if (imp) {
        cout << "-1\n";
    } else {
        cout << ans << '\n';
    }
}

int main() {
    cin.tie(0)->sync_with_stdio(0);
    int T;
    cin >> T;
    while (T--) solve();
}

verbatim earliest root score=100 submission #70931


Sliding Window Summation

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

## Description

Bessie has a hidden binary string $b_1 b_2\dots b_N$ ($1\le N\le 2\cdot 10^5$).

The only information about $b$ you are given is a binary string $r_1 r_2\dots r_{N-K+1}$ ($1\le K\le N$), where $r_i$ is the remainder when the number of ones in the length-$K$ window of $b$ with leftmost index $i$ is divided by two.

Output the minimum and maximum possible numbers of ones in Bessie's hidden binary string.

## Input Format

There are $T$ ($1\le T\le 10^3$) independent test cases to be solved. Each test is specified by the following:

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

The second line contains the binary string $r_1\dots r_{N-K+1}$, where $r_i = \sum_{j=i}^{i+K-1} b_j \pmod{2}$.

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

## Output Format

For each test case, output the minimum and maximum possible numbers of ones in Bessie's hidden binary string, separated by a single space.

## Examples

**Input 1**

```
7
5 1
10011
5 2
1001
5 3
100
5 5
0
5 5
1
4 4
1
5 2
0000
```

**Output 1**

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

## Note

For the first test case, $K = 1$ means that $r = b$, and the number of ones in $r$ is $3$.

For the second test case, there are two possibilities for $b$: $10001$ and $01110$, having $2$ and $3$ ones, respectively.

## Scoring

- Input 2: $N\le 8$
- Inputs 3-4: $K\le 8$ and the sum of $N$ over all tests does not exceed $10^4$
- Inputs 5-11: No additional constraints

**Problem credits:** Benjamin Qi

#include "testlib.h"
#include <string>
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 1000, "T");
    inf.readEoln();
    long long sumN = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(1, 1000000, "N");
        inf.readSpace();
        int K = inf.readInt(1, N, "K");
        inf.readEoln();
        sumN += N;
        std::string s = inf.readLine();
        int expect = N - K + 1;
        ensuref((int)s.size() == expect,
                "test %d: r has length %d, expected N-K+1=%d", tc, (int)s.size(), expect);
        for (char c : s)
            ensuref(c == '0' || c == '1',
                    "test %d: r contains non-binary char '%c'", tc, c);
    }
    ensuref(sumN <= 1000000, "sum N is %lld > 1000000", sumN);
    inf.readEof();
    return 0;
}

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

int main() {
    int T;
    scanf("%d", &T);
    while (T--) {
        int N, K;
        scanf("%d %d", &N, &K);
        static char buf[1000006];
        scanf("%s", buf);
        string r(buf);

        ll min_sum = 0;
        int parity = 0;
        ll min_dif = N;
        for (int i = 0; i < K; i++) {
            // candidate sequence for b[i, i+K, i+2K, ...]
            ll cnt = 1;
            ll cur = 0;      // cand[-1]
            ll cand_sum0 = 0; // sum of cand values
            // cand starts [0]
            cand_sum0 += cur;
            for (int j = i + K; j < N; j += K) {
                cur = cur ^ (r[j - K] - '0') ^ (r[j - K + 1] - '0');
                cand_sum0 += cur;
                cnt++;
            }
            ll cand_sum1 = cnt - cand_sum0;
            min_sum += min(cand_sum0, cand_sum1);
            if (cand_sum1 < cand_sum0) parity ^= 1;
            min_dif = min(min_dif, llabs(cand_sum0 - cand_sum1));
        }

        int r0 = r[0] - '0';
        ll get_min = min_sum + (ll)(parity != r0) * min_dif;
        ll get_max = N - min_sum - (ll)(((parity + K) & 1) != r0) * min_dif;
        printf("%lld %lld\n", get_min, get_max);
    }
    return 0;
}

hand C++ translation (earliest root AC #70932 was Python3)


COW Traversals

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

## Description

There are $N$ ($1\le N\le 2\cdot 10^5$) cows labeled $1\dots N$ on Farmer John's farm, where each cow lives in its own barn. Each cow $i$ has a best friend $a_i$ ($1\le a_i\le N$). Cows can be best friends with themselves, and multiple cows can have the same best friend. The cows love to party, so they have decided to throw a party for $M$ ($1\le M\le 2\cdot 10^5$) consecutive nights.

On night $i$, cow $c_i$ will decide to throw a party of type $t_i$ at its barn, where $t_i\in \texttt{"COW"}$. This party will exist for all future nights as well, until cow $c_i$ decides to throw a party of a different type.

Every night, each cow will attempt to go to a party. If a cow is not hosting a party, they will check their best friend's barn, and if there is no party there, will follow their best friend to wherever they are going (who might also follow their best friend and so on). It is possible that a cow might never find a party and will then give up for the night.

Compute for each night, the number of cows that end up at a party of type $C$, $O$, and $W$ respectively.

## Input Format

The first line contains $N$, the number of cows.

The second line contains $a_1,\dots, a_N$, where $a_i$ is cow $i$'s best friend.

The third line contains $M$, the number of nights.

The next $M$ lines each contain an integer $c_i$ ($1\le c_i\le N$) and a character $v_i$, representing the cow that is throwing the party and the party type respectively.

## Output Format

Output $M$ lines, where the $i$-th consists of $3$ space-separated integers, the number of cows going to parties of type $C$, $O$, and $W$ on the $i$-th night, respectively.

## Examples

**Input 1**

```
5
2 3 4 5 4
4
2 C
4 C
4 W
2 O
```

**Output 1**

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

## Note

On night $1$, there is only one party of type $C$ at barn $2$, which only cows $1$ and $2$ attend.

On night $2$, there is a new party of type $C$ at barn $4$, which cows $3$, $4$, and $5$ can now reach.

On night $3$, the party at barn $4$ is changed to type $W$, affecting cows $3$, $4$ and $5$.

On night $4$, the party at barn $2$ is changed to type $O$, affecting cows $1$ and $2$.

## Scoring

- Input 2: $N, M\le 100$
- Inputs 3-4: $N, M\le 4000$
- Inputs 5-9: $\{a_i\}$ is a permutation of $\{1,\dots, N\}$
- Inputs 10-21: No additional constraints

**Problem credits:** Benjamin Qi

#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, N, "a_i");
        if (i < N) inf.readSpace();
    }
    inf.readEoln();

    int M = inf.readInt(1, 200000, "M");
    inf.readEoln();

    for (int i = 1; i <= M; i++) {
        inf.readInt(1, N, "c_i");
        inf.readSpace();
        char v = inf.readChar();
        ensuref(v == 'C' || v == 'O' || v == 'W',
                "night %d: party type must be C/O/W, got '%c'", i, v);
        inf.readEoln();
    }

    inf.readEof();
    return 0;
}

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

vector<int> rt; // roots of each tree
struct dsu : vector<int> {
    dsu(int n) : vector(n, -1) {}
    int rep(int x) { return at(x) < 0 ? x : at(x) = rep(at(x)); }
    int sz(int x) { return -at(rep(x)); }
    bool same(int x, int y) { return rep(x) == rep(y); }
    bool join(int x, int y) {
        x = rep(x), y = rep(y);
        if (x == y) return 0;
        int r = rt[y];
        if (at(x) > at(y)) ::swap(x, y);
        at(x) += at(y);
        at(y) = x;
        rt[x] = r;
        return 1;
    }
};

int main() {
    cin.tie(0)->sync_with_stdio(0);
    int n; cin >> n;
    rt.resize(n + 1);
    vector<int> nx(n + 1);
    for (int i = 1; i <= n; i++) {
        cin >> nx[i];
        rt[i] = i;
    }
    int q; cin >> q;
    vector<int> qs(q);
    // ts[i] stores the operations applied at node i, from earliest to latest
    vector<vector<int>> ts(n + 1);
    char c;
    for (int &idx : qs) {
        cin >> idx >> c;
        int t;
        if (c == 'C') t = 0;
        else if (c == 'O') t = 1;
        else t = 2;
        ts[idx].push_back(t);
    }
    reverse(qs.begin(), qs.end()); // process queries backward
    dsu uf(n + 1); // our union-find data structure

    // join all non-parties to their parents
    for (int i = 1; i <= n; i++) if (!ts[i].size()) uf.join(i, nx[i]);
    array<int, 3> ans = {0, 0, 0}; // ans[i] = # of cows attending a party of type i
    for (int i = 1; i <= n; i++) if (ts[i].size()) {
        ans[ts[i].back()] += uf.sz(i);
    }
    vector<array<int, 3>> res = {ans};
    for (int i : qs) {
        assert(ts[i].size());
        ans[ts[i].back()] -= uf.sz(i);
        ts[i].pop_back();
        if (ts[i].size()) { // switch the type of this party from one to another
            ans[ts[i].back()] += uf.sz(i);
        }
        else { // delete this party and merge i into nx[i]
            int sz = uf.sz(i);
            uf.join(i, nx[i]);
            int r = rt[uf.rep(i)];
            if (ts[r].size()) ans[ts[r].back()] += sz;
        }
        res.push_back(ans);
    }
    reverse(res.begin(), res.end());
    res.erase(res.begin());
    for (auto &[c, o, w] : res) cout << c << " " << o << " " << w << "\n";
}

verbatim earliest root score=100 submission #70927


Milk Buckets

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

## Description

Bessie has challenged Farmer John to a game involving milk buckets! There are $N$ ($2 \le N \le 2\cdot 10^5$) milk buckets lined up in a row. The $i$-th bucket from the left initially contains $a_i$ ($0 \le a_i \le 10^9$) gallons of milk.

The game consists of two phases:

**Phase 1:** Farmer John may swap any two adjacent buckets. He may perform as many swaps as he likes, but each swap costs $1$ coin.

**Phase 2:** After swapping, Farmer John performs the following operation until only one bucket is left: Choose two adjacent buckets with milk amounts $a_i$ and $a_{i+1}$, and replace both buckets with one bucket containing $\frac{a_i + a_{i+1}}{2}$ gallons of milk in their place.

Your goal is to determine the minimum number of coins Farmer John must spend in the swapping phase to maximize the amount of milk in the final bucket after all merges are complete.

## Input Format

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

Then, for each test case, the first line contains an integer $N$: the number of milk buckets. The second line contains $N$ integers $a_1, a_2, \dots, a_N$, separated by spaces: the number of gallons of milk in each bucket.

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 the minimum number of coins Farmer John must spend to maximize the amount of milk in the final bucket.

## Examples

**Input 1**

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

**Output 1**

```
0
1
```

**Input 2**

```
4
4
9 4 9 2
6
0 0 2 0 0 0
3
2 0 1
9
3 3 3 10 3 2 13 14 13
```

**Output 2**

```
1
2
0
3
```

## Note

For the first test of the first example, we do not need to swap any milk buckets in the first phase. In the second phase, Farmer John can merge the first two buckets and then merge the only two buckets left to achieve a final amount of $0.5$. It can be shown that this final amount is maximal.

For the second test of the first example, we must perform a singular swap of the first two milk buckets in the first stage to achieve a final amount of $0.5$ in the second stage. It can be shown that we cannot achieve a final amount of $0.5$ without swaps in the first stage.

For the first test of the second example, Farmer John can swap the second and the third buckets in the first phase. Then, in the second phase, Farmer John can perform the following:

$$[9, 4, 9, 2] \to [9, 9, 4, 2] \to [9, 9, 3] \to [9, 6] \to [7.5]$$

(swap → merge buckets $3$ and $4$ → merge buckets $2$ and $3$ → merge buckets $1$ and $2$.)

The final amount of milk is $7.5$, which is the maximum possible. It can be shown that even with additional swaps, the final amount cannot exceed $7.5$, and that with fewer swaps, the final amount cannot reach $7.5$.

## Scoring

- Inputs 3-4: $a_i\le 1$ and $N\le 2000$ (sum of $N\le 5000$)
- Inputs 5-6: $a_i\le 1$
- Inputs 7-9: $N\le 2000$ (sum of $N\le 5000$)
- Inputs 10-14: No additional constraints

**Problem credits:** Charlie Yang

#include "testlib.h"

int main(int argc, char *argv[]) {
    registerValidation(argc, argv);

    int T = inf.readInt(1, 100, "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++) {
            inf.readInt(0, 1000000000, "a_i");
            if (i < n) inf.readSpace();
        }
        inf.readEoln();
    }
    ensuref(sumN <= 500000, "sum of N is %lld, must be <= 500000", sumN);

    inf.readEof();
    return 0;
}

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

struct BIT {
    int n;
    vector<int> t;
    BIT(int _n) : n(_n), t(n + 1) {}

    void add(int k, int x) {
        while(k <= n) {
            t[k] += x;
            k += k&-k;
        }
    }

    int sum(int r) {
        int sm = 0;
        while(r > 0) {
            sm += t[r];
            r -= r&-r;
        }
        return sm;
    }
};

void tc() {
    int N; cin >> N;

    vector<int> a(N);
    for(int i = 0; i < N; i++) cin >> a[i];
    vector<int> o(N); iota(o.begin(), o.end(), 0);
    sort(o.begin(), o.end(), [&] (int x, int y) {
        return a[x] < a[y];
    });

    BIT bit(N);
    int last = -1;
    vector<int> upds;
    long long ans = 0;
    for(int i : o) {
        if(last != a[i]) {
            for(int u : upds) {
                bit.add(u, 1);
            }
            upds.clear();
        }
        ans += min(bit.sum(N) - bit.sum(i + 1), bit.sum(i + 1));
        last = a[i];
        upds.push_back(i + 1);
    }
    cout << ans << endl;
}

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

    while(T--) {
        tc();
    }
}

verbatim earliest root score=100 submission #70928


Supervision

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

## Description

There are $N$ ($1\le N\le 10^6$) cows in cow camp, labeled $1\dots N$. Each cow is either a camper or a coach.

A nonempty subset of the cows will be selected to attend a field trip. If the $i$-th cow is selected, the cow will move to position $p_i$ ($0\le p_i\le 10^9$) on a number line, where the array $p$ is strictly increasing.

A nonempty subset of the cows is called "good" if for every selected camper, there is a selected coach within $D$ units to the left, inclusive ($0\le D\le 10^9$). How many good subsets are there, modulo $10^9 + 7$?

## Input Format

The first line contains two integers $N$ and $D$.

The next $N$ lines each contain two integers $p_i$ and $o_i$. $p_i$ denotes the position the $i$-th cow will move to. $o_i = 1$ means the $i$-th cow is a coach, whereas $o_i = 0$ means the $i$-th cow is a camper.

It is guaranteed that the $p_i$ are given in strictly increasing order.

## Output Format

Output the number of good subsets modulo $10^9 + 7$.

## Examples

**Input 1**

```
6 1
3 1
4 0
6 1
7 1
9 0
10 0
```

**Output 1**

```
11
```

**Input 2**

```
20 24
3 0
14 0
17 1
20 0
21 0
22 1
28 0
30 0
32 0
33 1
38 0
40 0
52 0
58 0
73 0
75 0
77 1
81 1
84 1
97 0
```

**Output 2**

```
13094
```

## Note

For the first example, the last two campers can never be selected. All other nonempty subsets work as long as if cow $2$ is selected, then cow $1$ is also selected.

## Scoring

- Input 3: $N = 20$
- Input 4: $D = 0$
- Inputs 5-8: $N\le 5000$
- Inputs 9-16: No additional constraints

**Problem credits:** Agastya Goel, Eva Zhu, and Benjamin Qi

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int N = inf.readInt(1, 1000000, "N");
    inf.readSpace();
    inf.readInt(0, 1000000000, "D");
    inf.readEoln();
    long long prev = -1;
    for (int i = 1; i <= N; i++) {
        int p = inf.readInt(0, 1000000000, "p_i");
        inf.readSpace();
        inf.readInt(0, 1, "o_i");
        inf.readEoln();
        ensuref(p > prev, "row %d: p must be strictly increasing (%d <= %lld)", i, p, prev);
        prev = p;
    }
    inf.readEof();
    return 0;
}

#include <bits/stdc++.h>
#define ll long long
#define rep(i, a, b) for(int i = (a); i <= (b); i++)
#define per(i, b, a) for(int i = (b); i >= (a); i--)
using namespace std;
const int N = 1e6 + 5, MOD = 1e9 + 7;
ll p, D, inv2 = (MOD + 1) / 2, qp[N], qg[N];
int main() {
    int n; scanf("%d%lld", &n, &D);
    ll mul = 1, inv_mul = 1, fsum = 0, gsum = 0;
    int headp = 1, tailp = 0;
    int headg = 1, tailg = 0;
    rep(i, 1, n){
        int o; scanf("%lld%d", &p, &o);
        while(headp <= tailp && qp[headp] < p-D){
            fsum = (fsum + (qg[headg] * mul)) % MOD;
            gsum = (gsum - qg[headg]) % MOD;
            headp++, headg++;
        }
        if(o == 0){
            mul = (mul * 2) % MOD;
            inv_mul = (inv_mul * inv2) % MOD;
        }
        else{
            ll total = (1 + fsum + gsum * mul % MOD) % MOD;
            ll x = (total * inv_mul) % MOD;
            qp[++tailp] = p, qg[++tailg] = x;
            gsum = (gsum + x) % MOD;
        }
    }
    ll ans = (fsum + (gsum * mul) % MOD) % MOD;
    printf("%lld\n", (ans + MOD) % MOD);
    return 0;
}

verbatim earliest root score=100 submission #70929


Hoof, Paper, Scissors Triples

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

## Description

You have probably heard of the game "Rock, Paper, Scissors". The cows like to play a similar game they call "Hoof, Paper, Scissors".

The rules of "Hoof, Paper, Scissors" are simple. Two cows play against each other. They both count to three and then each simultaneously makes a gesture that represents either a hoof, a piece of paper, or a pair of scissors. Hoof beats scissors (since a hoof can smash a pair of scissors), scissors beats paper (since scissors can cut paper), and paper beats hoof (since the hoof can get a papercut). For example, if the first cow makes a "hoof" gesture and the second a "paper" gesture, then the second cow wins. Of course, it is also possible to tie, if both cows make the same gesture.

Now there are $N$ ($3\le N\le 2\cdot 10^5$) cows who want to play hoof paper scissors, and they each independently have a strategy of drawing from some fixed distribution. In particular, the $i$-th cow's strategy is to play hoof, paper, or scissors with probabilities

$$\left(\frac{h_i}{h_i+p_i+s_i},\ \frac{p_i}{h_i+p_i+s_i},\ \frac{s_i}{h_i+p_i+s_i}\right),$$

respectively.

How many distinct triples of cows $(A, B, C)$ are there such that $A$ beats $B$ on average, $B$ beats $C$ on average, and $C$ beats $A$ on average? We consider two triples the same if one equals the other up to a cyclic shift.

## Input Format

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

The first line contains $N$.

The next $N$ lines each contain three non-negative integers $h_i$, $p_i$, $s_i$ ($0\le h_i, p_i, s_i\le 10^9$, $h_i+p_i+s_i>0$).

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

## Output Format

Output the number of triples.

**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**

```
2
4
1 0 0
1 0 0
0 1 0
0 0 1
10
20410069 21445597 257862632
114108992 287498302 113278897
607994331 143503714 631122722
337497016 270153603 320256324
633717786 631078144 493265815
202783212 612643590 560838949
713379081 42803063 58996167
293262767 470686180 220651551
656404313 408797935 345461691
959196297 827681918 591519393
```

**Output 1**

```
2
32
```

## Note

For the first test, there are two triples: $(1, 3, 4)$ and $(2, 3, 4)$.

## Scoring

- Inputs 2-3: $N\le 10$
- Inputs 4-9: $N\le 7500$, the sum of $N$ over all tests does not exceed $10^4$
- Inputs 10-21: No additional constraints

#include "testlib.h"

int main(int argc, char *argv[]) {
    registerValidation(argc, argv);

    int T = inf.readInt(1, 50000, "T");
    inf.readEoln();

    long long sumN = 0;
    for (int tc = 1; tc <= T; tc++) {
        int n = inf.readInt(3, 200000, "N");
        inf.readEoln();
        sumN += n;
        for (int i = 1; i <= n; i++) {
            int h = inf.readInt(0, 1000000000, "h");
            inf.readSpace();
            int p = inf.readInt(0, 1000000000, "p");
            inf.readSpace();
            int s = inf.readInt(0, 1000000000, "s");
            inf.readEoln();
            ensuref((long long)h + p + s > 0,
                    "test %d row %d: h+p+s must be > 0", tc, i);
        }
    }
    ensuref(sumN <= 300000,
            "sum of N over all tests is %lld, must be <= 300000", sumN);

    inf.readEof();
    return 0;
}

#include <bits/stdc++.h>
using namespace std;
struct Point {
    long long x, y;
};
long long cross(Point a, Point b) {
    return a.x * b.y - a.y * b.x;
}
int half(Point p) {
    return p.y > 0 || (p.y == 0 && p.x > 0) ? 1 : -1;
}
bool angleCmp(Point a, Point b) {
    int h1 = half(a), h2 = half(b);
    return h1 == h2 ? cross(a, b) > 0 : h1 < h2;
}
long long c3(long long n) {
    return n * (n - 1) * (n - 2) / 6;
}
long long c2(long long n) {
    return n * (n - 1) / 2;
}
void solve() {
    int N;
    cin >> N;
    vector<Point> points;
    for (int i = 0; i < N; ++i) {
        int r, p, s;
        cin >> r >> p >> s;
        p -= s, r -= s;
        if (p || r) points.push_back({(long long)p, (long long)r});
    }
    sort(points.begin(), points.end(), angleCmp);
    vector<pair<Point, long long>> points2;
    for (const auto& t : points) {
        if (!points2.empty() && !angleCmp(points2.back().first, t) && !angleCmp(t, points2.back().first)) {
            points2.back().second++;
        } else {
            points2.push_back({t, 1});
        }
    }
    long long ans = c3(points.size());
    int r = -1;
    long long sum = 0;
    int M = points2.size();
    for (int l = 0; l < M; ++l) {
        if (r < l) {
            r = l;
        } else {
            sum -= points2[l].second;
        }
        while (cross(points2[l].first, points2[(r + 1) % M].first) > 0) {
            ++r;
            sum += points2[r % M].second;
        }
        ans -= (c3(sum + points2[l].second) - c3(sum));
        if ((r + 1) % M != l && cross(points2[l].first, points2[(r + 1) % M].first) == 0) {
            ans -= c2(points2[l].second) * points2[(r + 1) % M].second;
            ans -= points2[l].second * sum * points2[(r + 1) % M].second;
        }
    }
    cout << ans << "\n";
}
int main() {
    cin.tie(0)->sync_with_stdio(0);
    int TC;
    cin >> TC;
    while (TC--) solve();
    return 0;
}

verbatim earliest root score=100 submission #70924


Lineup Counting Queries

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

## Description

There is a line of cows, initially (i.e. at time $t = 0$) containing only cow $0$ at position $0$ (here, a cow is at position $k$ if there are $k$ cows in front of it). At time $t$ for $t = 1, 2, 3, \dots$, the cow at position $0$ moves to position $\lfloor t/2\rfloor$, every cow in positions $1 \dots \lfloor t/2\rfloor$ moves forward one position, and cow $t$ joins the line at the end of the line (position $t$).

Answer $Q$ ($1\le Q\le 10^5$) independent queries each of the following form:

Out of cows $l_1\dots r_1$, how many are located at positions $l_2\dots r_2$ immediately after time $t$?

($0\le l_1\le r_1\le t,\ 0\le l_2\le r_2 \le t,\ t\le 10^{18}$)

## Input Format

The first line contains $Q$, the number of queries.

The next $Q$ lines each contain five integers specifying a query of the form "$l_1\ r_1\ l_2\ r_2\ t$."

## Output Format

Output the answer to each query on a separate line.

## Examples

**Input 1**

```
4
0 9 0 9 9
3 5 4 5 9
4 5 3 5 9
1 1 3 3 9
```

**Output 1**

```
10
2
1
1
```

**Input 2**

```
1
0 1000000000000000000 0 1000000000000000000 1000000000000000000
```

**Output 2**

```
1000000000000000001
```

## Note

Lineups at various times:

```
t = 0 | 0
t = 1 | 0 1
t = 2 | 1 0 2
t = 3 | 0 1 2 3
t = 4 | 1 2 0 3 4
t = 5 | 2 0 1 3 4 5
t = 6 | 0 1 3 2 4 5 6
t = 7 | 1 3 2 0 4 5 6 7
t = 8 | 3 2 0 4 1 5 6 7 8
t = 9 | 2 0 4 1 3 5 6 7 8 9
```

At $t = 9$ the cows from front to back are $[2, 0, 4, 1, 3, 5, 6, 7, 8, 9]$.

To answer the third query, the cows at positions $3\dots 5$ are $[1, 3, 5]$, and only one of them is in the range $4\dots 5$.

## Scoring

- Input 3: $Q\le 1000$, $t\le 100$
- Inputs 4-7: $l_1 = r_1$ for all queries
- Inputs 8-14: $r_1 \le 2\cdot l_1$ for all queries
- Inputs 15-21: No additional constraints

**Problem credits:** Agastya Goel and Benjamin Qi

#include "testlib.h"

const long long MAXT = 1000000000000000000LL; // 1e18

int main(int argc, char *argv[]) {
    registerValidation(argc, argv);

    int Q = inf.readInt(1, 100000, "Q");
    inf.readEoln();

    for (int q = 1; q <= Q; q++) {
        long long l1 = inf.readLong(0, MAXT, "l1");
        inf.readSpace();
        long long r1 = inf.readLong(0, MAXT, "r1");
        inf.readSpace();
        long long l2 = inf.readLong(0, MAXT, "l2");
        inf.readSpace();
        long long r2 = inf.readLong(0, MAXT, "r2");
        inf.readSpace();
        long long t = inf.readLong(0, MAXT, "t");
        inf.readEoln();

        ensuref(l1 <= r1, "query %d: need l1 <= r1 (%lld > %lld)", q, l1, r1);
        ensuref(r1 <= t,  "query %d: need r1 <= t (%lld > %lld)", q, r1, t);
        ensuref(l2 <= r2, "query %d: need l2 <= r2 (%lld > %lld)", q, l2, r2);
        ensuref(r2 <= t,  "query %d: need r2 <= t (%lld > %lld)", q, r2, t);
    }

    inf.readEof();
    return 0;
}

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

vector<long long> inv(long long n){
    vector<long long> ans;
    ans.push_back(4000000000000000000);
    for(int i=0;i<111;i++){
        ans.push_back(n);
        n = (2*n+4)/3-2;
    }
    return ans;
}

int main(){
    int q;
    cin >> q;
    while(q--){
        long long l1,r1,l2,r2,t;
        cin >> l1 >> r1 >> l2 >> r2 >> t;

        long long ans = 0;
        vector<long long> inv1 = inv(t-1);
        vector<long long> inv2 = inv(l2+t-1);
        vector<long long> inv3 = inv(r2+t);
        for(int j=1;j<111;j++){
            // l1 <= i <= min(t/2,r1)
            // 3*i-1 <= min(inv1[j-1],inv3[j])
            // 3*i-1 > inv2[j]
            long long low = max(l1,(inv2[j]+4)/3);
            long long high = min(min(t/2,r1),(min(inv1[j-1],inv3[j])+4)/3-1);
            ans += max(0LL,high-low+1);
        }

        // l1 <= i <= r1
        // l2 <= i <= r2
        // t <= 2*i-1
        ans += max(0LL,min(r1,r2)-max(max(l1,l2),t/2+1)+1);
        cout << ans << endl;
    }
}

verbatim earliest root score=100 submission #70925


Pluses and Minuses

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

## Description

Farmer John once painted a rectangular grid on the ground of his pasture. In each cell, he painted either a $+$ or a $-$ (representing $+1$ and $-1$, respectively).

Over time, the paint faded, and Farmer John now remembers the values of only some cells. However, Farmer John does remember one important fact about the original painting:

> In every row and every column, the sum of the values in any contiguous subsegment was always between $-1$ and $2$ (inclusive).

As an example, consider the row `+ - - +`. It does not satisfy the condition, since the subsegment `+ [ - - ] +` has sum $-2$.

However, the row `- + + -` does satisfy the condition.

```
[ - ] + + -    sum = -1
[ - + ] + -    sum =  0
[ - + + ] -    sum = +1
[ - + + - ]    sum =  0
- [ + ] + -    sum = +1
- [ + + ] -    sum = +2
- [ + + - ]    sum = +1
- + [ + ] -    sum = +1
- + [ + - ]    sum =  0
- + + [ - ]    sum = -1
```

Count the number of different grids consistent with Farmer John's memory.

## Input Format

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

The first line contains $R$, $C$, and $X$ ($1\le R, C\le 5\cdot 10^5$, $0\le X\le \min(10^5, RC)$), meaning that the grid has dimensions $R\times C$ and Farmer John remembers the values of $X$ different cells in the grid.

Then following $X$ lines each contain a character $v\in \{+, -\}$ followed by two integers $r$ and $c$ ($1\le r\le R$, $1\le c\le C$), meaning that the value at the $r$-th row and $c$-th column of the grid is $v$. It is guaranteed that no ordered pair $(r, c)$ appears more than once within a single test.

Additionally, it is guaranteed that neither the sum of $R$ nor the sum of $C$ over all tests exceeds $10^6$, and that the sum of $X$ over all tests does not exceed $2\cdot 10^5$.

## Output Format

For each test, output the number of grids on a separate line.

## Examples

**Input 1**

```
2
1 3 3
+ 1 3
+ 1 1
- 1 2
1 3 3
+ 1 1
+ 1 3
+ 1 2
```

**Output 1**

```
1
0
```

**Input 2**

```
1
2 2 0
```

**Output 2**

```
7
```

## Note

For the second example, here are the seven grids:

```
++    ++    ++    +-    +-    -+    -+
++    +-    -+    ++    -+    ++    +-
```

## Scoring

- Inputs 3-4: $\min(R, C) = 1$ for all tests
- Inputs 5-6: $R, C\le 10$ for all tests
- Inputs 7-11: $\sum \max(R, C)^2 \le 10^6$
- Inputs 12-14: $\sum RC \le 10^6$
- Inputs 15-22: No additional constraints

**Problem credits:** Alex Chen

#include "testlib.h"
#include <set>
#include <utility>

int main(int argc, char *argv[]) {
    registerValidation(argc, argv);

    int T = inf.readInt(1, 100, "T");
    inf.readEoln();

    long long sumR = 0, sumC = 0, sumX = 0;
    for (int tc = 1; tc <= T; tc++) {
        int R = inf.readInt(1, 500000, "R");
        inf.readSpace();
        int C = inf.readInt(1, 500000, "C");
        inf.readSpace();
        long long RC = (long long)R * C;
        long long xhi = RC < 100000 ? RC : 100000;
        int X = inf.readInt(0, (int)xhi, "X");
        inf.readEoln();

        sumR += R;
        sumC += C;
        sumX += X;

        std::set<std::pair<int,int>> seen;
        for (int i = 1; i <= X; i++) {
            char v = inf.readChar();
            ensuref(v == '+' || v == '-',
                    "test %d cell %d: value must be + or -, got '%c'", tc, i, v);
            inf.readSpace();
            int r = inf.readInt(1, R, "r");
            inf.readSpace();
            int c = inf.readInt(1, C, "c");
            inf.readEoln();
            ensuref(seen.insert({r, c}).second,
                    "test %d: duplicate cell (%d, %d)", tc, r, c);
        }
    }
    ensuref(sumR <= 1000000, "sum of R is %lld, must be <= 1000000", sumR);
    ensuref(sumC <= 1000000, "sum of C is %lld, must be <= 1000000", sumC);
    ensuref(sumX <= 200000,  "sum of X is %lld, must be <= 200000", sumX);

    inf.readEof();
    return 0;
}

#include <bits/stdc++.h>

using i64 = long long;

struct Cell {
  int v, r, c;
};

void tc() {
  int r, c, x;
  std::cin >> r >> c >> x;

  std::vector<Cell> cl(x);
  for (auto& [v, ri, ci] : cl) {
    char cc;
    std::cin >> cc >> ri >> ci;
    v = cc == '+';
    --ri;
    --ci;
  }

  if (r == 1 && c == 1) {
    if (x == 1)
      std::cout << 1 << '\n';
    else
      std::cout << 2 << '\n';
    return;
  }

  auto get_mi_rb = [&](int d) {
    int mx = std::max(r, c);
    if (mx % 2 == 0)
      return d + mx - 1;
    return d + mx;
  };

  auto comp = [&](int mi, int rb) {
    if (mi > rb)
      return 0;
    return (rb - mi) / 2 + 1;
  };

  i64 ans = 0;
  auto solve = [&](bool z) {
    std::vector vals(r + c - 1, -1);
    for (auto [v, ri, ci] : cl) {
      if (vals[ri + ci] == -1)
        vals[ri + ci] = v;
      else if (vals[ri + ci] != v)
        return;
    }
    bool ff = vals[0] == -1, fl = vals[r + c - 2] == -1;
    for (int fval : {0, 1}) {
      if (!ff && vals[0] != fval)
        continue;
      vals[0] = fval;
      for (int lval : {0, 1}) {
        if (!fl && vals[r + c - 2] != lval)
          continue;
        vals[r + c - 2] = lval;
        std::vector<int> d;
        for (int i = 0; i < r + c - 1; ++i) {
          if (vals[i] != -1)
            d.push_back(i);
        }
        std::pair i1{-1, -1}, i2{-1, -1};
        bool g = true;
        for (int i = 0; i < (int)d.size() - 1; ++i) {
          int lb = d[i], rb = d[i + 1];
          if ((vals[lb] ^ vals[rb]) != (rb - lb) % 2) {
            if (i1.first == -1)
              i1 = {lb, rb};
            else if (i2.first == -1)
              i2 = {lb, rb};
            else {
              g = false;
              break;
            }
          }
        }
        if (!g)
          continue;

        if (i1.first == -1) {
          if (z)
            ++ans;
          for (int i = 0; i < (int)d.size() - 1; ++i) {
            int L = d[i], R = d[i + 1];
            for (int lb = vals[L] == 1 ? L + 1 : L + 2; get_mi_rb(lb) <= R; lb += 2)
              ans += comp(get_mi_rb(lb), R);
          }
        } else if (i2.first == -1) {
          auto [L, R] = i1;
          if (vals[L] == 1)
            ans += comp(L + 1, R);
          else
            ans += comp(L + 2, R);
        } else {
          auto [l1, r1] = i1;
          auto [l2, r2] = i2;
          for (int lb = vals[l1] == 1 ? l1 + 1 : l1 + 2; lb <= r1; lb += 2) {
            int rb = std::max(get_mi_rb(lb), vals[l2] == 1 ? l2 + 1 : l2 + 2);
            ans += comp(rb, r2);
          }
        }
      }
    }
  };
  solve(true);
  if (std::min(r, c) > 1) {
    for (auto& [v, ri, ci] : cl)
      ci = c - 1 - ci;
    solve(false);
  }

  if (r == 2 && c == 2) {
    bool g = true;
    for (auto [v, ri, ci] : cl) {
      if (v == 0) {
        g = false;
        break;
      }
    }
    if (g)
      --ans;
  }

  std::cout << ans << '\n';
}

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

  int t;
  std::cin >> t;
  while (t--)
    tc();
}

verbatim earliest root score=100 submission #70926


It's Mooin' Time IV

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

## Description

Bessie has a computer with a keyboard that only has two letters, `M` and `O`.

Bessie wants to type her favorite moo $S$ consisting of $N$ letters, each of which is either an `M` or an `O`. However, her computer has been hit with a virus. Every time she tries to type the letter `O`, every letter that she has typed so far flips, either from `M` to `O` or from `O` to `M`, before the `O` appears.

Is it possible for Bessie to type out her favorite moo?

Additionally, Bessie is given a parameter $k$ which is either $0$ or $1$.

- If $k = 0$, then Bessie only needs to determine whether it is possible to type out her favorite moo.
- If $k = 1$, then Bessie also needs to give an example of a sequence of keystrokes to type so she can type out her favorite moo.

## Input Format

The first line contains $T$, the number of independent test cases ($1\le T\le 10^4$) and $k$ ($0\le k\le 1$).

The first line of each test case has $N$ ($1\le N\le 2\cdot 10^5$).

The second line of each test case has $S$. It is guaranteed that no characters will appear in $S$ besides $\texttt{M}$ and $\texttt{O}$.

The sum of $N$ across all test cases will not exceed $4\cdot 10^5$.

## Output Format

For each test case, output either one or two lines using the following procedure.

If it is impossible for Bessie to type out $S$, print $\texttt{NO}$ on a single line.

Otherwise, on the first line print $\texttt{YES}$. Furthermore, if $k = 1$, on the second line, print a string of length $N$, the characters in order that Bessie needs to type in order to type out her favorite moo. If there are multiple such strings, any will be accepted.

## Examples

**Input 1**

```
2 0
3
MOO
5
OOMOO
```

**Output 1**

```
YES
YES
```

**Input 2**

```
2 1
3
MOO
5
OOMOO
```

**Output 2**

```
YES
OMO
YES
MOOMO
```

## Note

As Bessie types out $\texttt{MOOMO}$, this is how the letters change:

- Before typing the first $\texttt{M}$, Bessie has an empty string. Afterwards, she has the string $\texttt{M}$.
- After typing the first $\texttt{O}$, the $\texttt{M}$ flips to $\texttt{O}$, and then the $\texttt{O}$ is appended to form $\texttt{OO}$.
- After typing the second $\texttt{O}$, the $\texttt{OO}$ flips to $\texttt{MM}$, and then the $\texttt{O}$ is appended to form $\texttt{MMO}$.
- After typing the second $\texttt{M}$, Bessie has the string $\texttt{MMOM}$.
- After typing the last $\texttt{O}$, the string $\texttt{MMOM}$ flips to $\texttt{OOMO}$, and then the $\texttt{O}$ is appended to form $\texttt{OOMOO}$, as desired.

## Scoring

- Inputs 3-4: $k = 0$
- Inputs 5-6: $k = 1$, $T\le 10^3$, $N\le 10$
- Inputs 7-9: $k = 1$, $T\le 10$, $N\le 1000$
- Inputs 10-16: $k = 1$

**Problem credits:** Nick Wu

#include "testlib.h"
#include <string>
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 10000, "T"); inf.readSpace();
    inf.readInt(0, 1, "k"); 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::string s = inf.readLine();
        ensuref((int)s.size() == N, "test %d: |S|=%d expected %d", tc, (int)s.size(), N);
        for (char c : s) ensuref(c == 'M' || c == 'O', "test %d: char must be M/O got '%c'", tc, c);
    }
    ensuref(sumN <= 400000, "sum N %lld > 4e5", sumN);
    inf.readEof(); return 0;
}

#include <iostream>

using namespace std;

int main() {
  int t, mode;
  cin >> t >> mode;
  while(t--) {
    int n;
    string s;
    cin >> n >> s;
    cout << "YES\n";
    if(mode == 0) continue;
    for(int i = 0; i+1 < n; i++) {
      if(s[i] == s[i+1]) cout << 'M';
      else cout << 'O';
    }
    cout << s.back() << "\n";
  }
}

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

static string simulate(const string &keys) {
    int n = keys.size();
    string s(n, '?');
    int suffO = 0; // number of 'O' strictly after position i, computed right-to-left
    for (int i = n - 1; i >= 0; --i) {
        char base = keys[i];
        // 'O' at position i is appended at that step; subsequent O's flip it suffO times.
        // 'M' at position i is appended; subsequent O's flip it suffO times.
        bool flip = (suffO & 1);
        char out = base;
        if (flip) out = (out == 'M' ? 'O' : 'M');
        s[i] = out;
        if (keys[i] == 'O') suffO++;
    }
    return s;
}

int main(int argc, char *argv[]) {
    setName("USACO 2026 Bronze: Mooin' Time IV");
    registerTestlibCmd(argc, argv);

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

    for (int t = 1; t <= T; t++) {
        int N = inf.readInt();
        string S = inf.readToken();
        if ((int)S.size() != N) quitf(_fail, "judge input malformed at test %d", t);

        string ansVerdict = ans.readToken();      // YES or NO
        string oufVerdict = ouf.readToken();
        if (ansVerdict != "YES" && ansVerdict != "NO")
            quitf(_fail, "reference output malformed at test %d: %s", t, ansVerdict.c_str());
        if (oufVerdict != "YES" && oufVerdict != "NO")
            quitf(_wa, "test %d: contestant verdict must be YES or NO, got '%s'", t, oufVerdict.c_str());
        if (ansVerdict != oufVerdict)
            quitf(_wa, "test %d: verdict differs (expected %s, got %s)", t, ansVerdict.c_str(), oufVerdict.c_str());

        if (K == 1 && ansVerdict == "YES") {
            string oufKeys = ouf.readToken();
            if ((int)oufKeys.size() != N)
                quitf(_wa, "test %d: keystroke string length %d, expected %d", t, (int)oufKeys.size(), N);
            for (char c : oufKeys)
                if (c != 'M' && c != 'O')
                    quitf(_wa, "test %d: keystroke string contains invalid char '%c'", t, c);
            string produced = simulate(oufKeys);
            if (produced != S)
                quitf(_wa, "test %d: keystrokes '%s' produce '%s', expected '%s'",
                      t, oufKeys.c_str(), produced.c_str(), S.c_str());

            // also consume reference's keystroke if present (it is, since reference says YES)
            if (!ans.seekEof()) ans.readToken();
        }
    }

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

verbatim earliest root score=100 submission #70970


Moo Hunt

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

## Description

Bessie is playing the popular game "Moo Hunt". In this game, there are $N$ ($3\le N\le 20$) cells in a line, numbered from $1$ to $N$. All cells either have the character $M$ or $O$ with the $i$-th cell having character $s_i$.

Bessie plans to perform $K$ ($1\le K\le 2\cdot 10^5$) mooves. On her $i$-th moove, Bessie will tap $3$ different cells ($x_i, y_i, z_i$) ($1\le x_i, y_i, z_i\le N$). Bessie will earn a point if $s_{x_i} = M$ and $s_{y_i} = s_{z_i} = O$. In other words, Bessie will earn a point if she forms the string $MOO$ by tapping cells $x_i, y_i, z_i$ in that order.

Farmer John wants to help Bessie get a new high score. He wants you to find the maximum possible score Bessie could get across all possible boards if she performs the $K$ mooves as well as the number of different boards that will allow Bessie to achieve this maximum possible score. Two boards are different if there exists a cell such that the corresponding characters at the cell are different.

## Input Format

The first line contains $N$ and $K$, the number of cells and the number of mooves Bessie will perform.

Each of the next $K$ lines contains $x_i, y_i, z_i$ describing Bessie's $i$-th move ($x_i, y_i, z_i$ are pairwise distinct).

## Output Format

Output the maximum possible score Bessie could achieve, followed by the count of different boards that will allow Bessie to achieve this maximum score.

## Examples

**Input 1**

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

**Output 1**

```
4 2
```

**Input 2**

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

**Output 2**

```
6 3
```

## Note

For the first example, the boards $MOOOM$ and $MOOMM$ allow Bessie to achieve a maximum score of $4$. In both boards, Bessie will earn points on mooves $1, 2, 5, 6$. It can be shown that this is the maximum score Bessie can achieve, and those two boards are the only possible boards allowing Bessie to achieve a score of $4$.

For the second example, the boards that allow Bessie to achieve a maximum possible score of $6$ are $OOMOOO$, $OOMMOO$, and $OOMOOM$.

## Scoring

- Inputs 3-5: $N\le 8$, $K\le 10^4$
- Inputs 6-12: There will be one test for each $N\in \{14, 15, 16, 17, 18, 19, 20\}$ with no additional constraints on $K$

**Problem credits:** Alex Liang

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int N = inf.readInt(3, 20, "N"); inf.readSpace();
    int K = inf.readInt(1, 200000, "K"); inf.readEoln();
    for (int i = 1; i <= K; i++) {
        int x = inf.readInt(1, N, "x"); inf.readSpace();
        int y = inf.readInt(1, N, "y"); inf.readSpace();
        int z = inf.readInt(1, N, "z"); inf.readEoln();
        ensuref(x != y && y != z && x != z, "moove %d: x,y,z must be pairwise distinct (%d %d %d)", i, x, y, z);
    }
    inf.readEof(); return 0;
}

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

int main(){
    int n, k;
    cin >> n >> k;

    vector<vector<vector<int>>> isAt(n, vector<vector<int>>(n, vector<int>(n, 0)));

    for (int i = 0; i < k; i++) {
        int x, y, z;
        cin >> x >> y >> z;
        x--; y--; z--;
        isAt[x][y][z]++;
    }

    vector<int> score((1 << n), 0);

    for (int msk = 1; msk < (1 << n); msk++) {
        int msb = 31 - __builtin_clz(msk);
        vector<int> mpos, opos;

        for (int i = 0; i < n; i++) {
            if ((1 << i) & msk)
                mpos.push_back(i);
            else
                opos.push_back(i);
        }

        // Previously
        score[msk] = score[msk ^ (1 << msb)];

        // Turned bad from flipping MSB
        for (int m : mpos)
            for (int o : opos)
                score[msk] -= isAt[m][msb][o] + isAt[m][o][msb];

        // Turned good from flipping MSB
        for (int o1 : opos)
            for (int o2 : opos)
                score[msk] += isAt[msb][o1][o2];
    }
    int bestVal = *max_element(score.begin(), score.end());
    int bestCount = count(score.begin(), score.end(), bestVal);

    cout << bestVal << " " << bestCount << "\n";
}

verbatim earliest root score=100 submission #70946


Purchasing Milk

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

## Description

On National Milk Day, Farmer John is offering exclusive prices on buckets of milk! He has $N$ ($1\le N\le 10^5$) deals numbered from $1$ to $N$. For the $i$-th deal, he is offering $2^{i-1}$ buckets of milk for $a_i$ ($1\le a_i\le 10^9$, $a_i < a_{i+1}$) moonies. The same deal may be taken any non-negative integer number of times.

You are thinking about $Q$ ($1\le Q\le 10^4$) independent queries. For each query, you have an integer $x$ ($1\le x\le 10^9$) in mind and wonder what is the minimum cost to purchase at least $x$ buckets of milk.

## Input Format

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

The following line contains $a_1, a_2, \ldots, a_N$.

Each of the following $Q$ lines contains an integer $x$, representing a query.

## Output Format

For each query, output the minimum cost on a new line.

**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**

```
2 4
10 15
1
2
6
7
```

**Output 1**

```
10
15
45
55
```

**Input 2**

```
4 10
10 25 30 70
1
2
3
4
5
6
7
8
15
101
```

**Output 2**

```
10
20
30
30
40
50
60
60
120
760
```

## Note

For the first example, Farmer John is offering 2 deals: $1$ bucket of milk for $10$ moonies and $2$ buckets of milk for $15$ moonies.

The cheapest cost to buy $1$ bucket is just the cost of the $1$ bucket deal and the cheapest cost to buy $2$ buckets is just the cost of the $2$ bucket deal.

To get $6$ buckets, the cheapest way is to purchase $3$ of the $2$ bucket deal for a total of $45$ moonies.

To get $7$ buckets, the cheapest way is to purchase $3$ of the $2$ bucket deal and $1$ of the $1$ bucket deal for a total of $55$ moonies.

For the second example, Farmer John is offering a total of $4$ deals for $1, 2, 4$, and $8$ buckets. For each of the $10$ queries, the corresponding output indicates the minimum cost to purchase at least that amount of milk. Sometimes, it is cheaper to purchase more than the specified amount.

## Scoring

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

**Problem credits:** Chongtian Ma

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int N = inf.readInt(1, 100000, "N"); inf.readSpace();
    int Q = inf.readInt(1, 10000, "Q"); inf.readEoln();
    long long prev = 0;
    for (int i = 1; i <= N; i++) {
        int a = inf.readInt(1, 1000000000, "a_i");
        if (i > 1) ensuref(a > prev, "a must be strictly increasing (idx %d: %d <= %lld)", i, a, prev);
        prev = a;
        if (i < N) inf.readSpace();
    }
    inf.readEoln();
    for (int q = 1; q <= Q; q++) { inf.readInt(1, 1000000000, "x"); inf.readEoln(); }
    inf.readEof(); return 0;
}

#include <stdio.h>
#include <stdint.h>
#include <limits.h>
#include <algorithm>
using namespace std;

void solve()
{
    int N, K, Q;
    scanf("%d %d", &N, &Q);

    int price[N];
    scanf("%d", &price[0]);
    for (int idx = 1; idx < N; ++idx)
    {
        scanf("%d", &price[idx]);
        price[idx] = min(price[idx], 2 * price[idx-1]);
    }

    for (int idx = 0; idx < Q; ++idx)
    {
        int x;
        scanf("%d", &x);

        long long minCost = 1e18;
        long long curCost = 0;
        for (int jdx = min(30, N-1); jdx >= 0; --jdx)
        {
            int curBuckets = 1<<jdx;
            long long count = x / curBuckets;

            x -= count*curBuckets;
            curCost += count*price[jdx];

            if (x == 0)
                minCost = min(minCost, curCost);
            else
                minCost = min(minCost, curCost + price[jdx]);
        }

        printf("%lld\n", minCost);
    }
}

int main()
{
    solve();

    return 0;
}

verbatim earliest root score=100 submission #70947


Cow-libi 2

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

## Description

Farmer John and Farmer Nhoj have taken their respective cows to sit around a campfire in hopes of settling their personal differences. In total, there are $N$ ($2\le N\le 10^5$) cows sitting in a circular formation. When the farmers are ready to take their cows back to their farms, they realize one crucial mistake: since all the cows look the same and are mixed up, they are unable to identify which cows belong to which farmer!

Then the $N$ cows are organized into one straight line to be interrogated by the two farmers.

Because of the confusion, the order of the cows in the line, from $1$ to $N$, might not correspond to their circular order around the campfire.

But the cows want to play a game. Instead of answering directly which farmer they belong to, they say which farmer the cows *adjacent to them in the original circle* belong to. Additionally, it is known that Farmer Nhoj's cows always lie but Farmer John raised his cows well and they will always tell the truth.

Given the statements of the cows, is it possible to assign each cow to either Farmer John or Farmer Nhoj such that the statements of the cows assigned to Farmer John are all true, and the statements of the cows assigned to Farmer Nhoj are all false?

## Input Format

The first line contains $T$ ($1\le T\le 1000$), the number of independent test cases, and an integer $C\in \{0, 1\}$ (whether to output a construction or not).

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

The following line contains a string of length $N$ containing characters `J` or `N`. The $i$-th character is `J` if cow $i$ claims the cow to their *left* in the circle belongs to Farmer John, or Farmer Nhoj otherwise.

The following line contains a string of length $N$ containing characters `J` or `N`. The $i$-th character is `J` if cow $i$ claims the cow to their *right* in the circle belongs to Farmer John, or Farmer Nhoj otherwise.

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

## Output Format

For each test case, output `YES` or `NO`.

Additionally, if $C = 1$ and the answer is `YES`, output two more lines describing your construction:

- The first line should contain a permutation $p_1, p_2, \dots, p_N$ of $1\dots N$, representing the circular order of the cows around the campfire, where cow $p_i$ is to the left of cow $p_{i+1}$ for $i$ in $1\dots N - 1$, and cow $p_N$ is to the left of cow $p_1$.
- The second line should contain a string $b_1 b_2 \dots b_N$ consisting only of `J`s and `N`s, meaning that cow $p_i$ belongs to Farmer John if $b_i$ is `J`, or Farmer Nhoj otherwise.

Any valid construction will be accepted.

## Examples

**Input 1**

```
6 0
3
JJJ
JJJ
4
JJNJ
NJJJ
6
NJNJNJ
JNNJNJ
4
NNNN
NNNN
3
NNN
NNN
5
JJNNJ
NJNJJ
```

**Output 1**

```
YES
NO
NO
YES
NO
YES
```

**Input 2**

```
6 1
3
JJJ
JJJ
4
JJNJ
NJJJ
6
NJNJNJ
JNNJNJ
4
NNNN
NNNN
3
NNN
NNN
5
JJNNJ
NJNJJ
```

**Output 2**

```
YES
1 2 3
JJJ
NO
NO
YES
1 2 3 4
NJNJ
NO
YES
4 5 2 1 3
JJJJN
```

## Note

Consider the output for the sixth test case. Cows $1, 2, 4, 5$ belong to Farmer John, and Cow $3$ belongs to Farmer Nhoj.

The cows will then behave as follows:

- Cow $1$'s left and right neighbours are Cow $2$ and Cow $3$, respectively. Cow $1$ says that Cow $2$ belongs to Farmer John, and Cow $3$ belongs to Farmer Nhoj.
- Cow $2$'s left and right neighbours are Cow $5$ and Cow $1$, respectively. Cow $2$ says that both cows belong to Farmer John.
- Cow $3$'s left and right neighbours are Cow $1$ and Cow $4$, respectively. Cow $3$ (dishonestly) says that both cows belong to Farmer Nhoj.
- Cow $4$'s left and right neighbours are Cow $3$ and Cow $5$, respectively. Cow $4$ says that Cow $3$ belongs to Farmer Nhoj, and Cow $5$ belongs to Farmer John.
- Cow $5$'s left and right neighbours are Cow $4$ and Cow $2$, respectively. Cow $5$ says that both cows belong to Farmer John.

All these claims are consistent with the input.

## Scoring

- Input 3: $C = 0$ and $N\le 10$
- Input 4: $C = 1$ and $N\le 10$
- Inputs 5-8: $C = 0$
- Inputs 9-12: $C = 1$

**Problem credits:** Chongtian Ma

#include "testlib.h"
#include <string>
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 1000, "T"); inf.readSpace();
    inf.readInt(0, 1, "C"); inf.readEoln();
    long long sumN = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(2, 100000, "N"); inf.readEoln();
        sumN += N;
        for (int line = 0; line < 2; line++) {
            std::string s = inf.readLine();
            ensuref((int)s.size() == N, "test %d line %d: length %d expected %d", tc, line+1, (int)s.size(), N);
            for (char c : s)
                ensuref(c == 'J' || c == 'N', "test %d line %d: char must be J/N, got '%c'", tc, line+1, c);
        }
    }
    ensuref(sumN <= 500000, "sum N is %lld > 5e5", sumN);
    inf.readEof();
    return 0;
}

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

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int t, c; cin >> t >> c;
    while (t--) {
        int n; cin >> n;
        string a, b; cin >> a >> b;
        vector<vector<array<int, 2>>> g(2);
        int cnt[2][2] = {};
        FOR(i, 0, n) {
            int u = a[i] == 'N', v = b[i] == 'N';
            g[u].push_back({v, i});
            cnt[u][v]++;
        }
        bool ans = count(all(a), 'J') == count(all(b), 'J')
            and count(all(a), 'N') % 2 == 0
            and (!cnt[0][0] or !cnt[1][1] or cnt[0][1] or cnt[1][0]);
        if (ans) cout << "YES" << nl;
        else cout << "NO" << nl;
        if (!c or !ans) continue;
        int st = sz(g[0]) ? 0 : 1;
        vi p;
        auto dfs = [&] (auto dfs, int u) -> void {
            while (sz(g[u])) {
                auto [v, i] = g[u].back();
                g[u].pop_back();
                dfs(dfs, v);
                p.push_back(i);
            }
        };
        dfs(dfs, st);
        reverse(all(p));
        FOR(i, 0, n) cout << p[i] + 1 << " \n"[i == n - 1];
        int l = 0;
        cout << "J";
        FOR(i, 1, n) {
            if (a[p[i]] == 'N') l = 1 - l;
            cout << "JN"[l];
        }
        cout << nl;
    }
}

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

int main(int argc, char *argv[]) {
    setName("USACO 2026 Silver: Cow-libi 2");
    registerTestlibCmd(argc, argv);

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

    for (int t = 1; t <= T; t++) {
        int N = inf.readInt();
        string L = inf.readToken();
        string R = inf.readToken();
        if ((int)L.size() != N || (int)R.size() != N)
            quitf(_fail, "judge input malformed at test %d", t);

        string ansVerdict = ans.readToken();
        string oufVerdict = ouf.readToken();
        if (ansVerdict != "YES" && ansVerdict != "NO")
            quitf(_fail, "reference verdict bad: %s", ansVerdict.c_str());
        if (oufVerdict != "YES" && oufVerdict != "NO")
            quitf(_wa, "test %d: contestant verdict must be YES or NO, got '%s'", t, oufVerdict.c_str());
        if (ansVerdict != oufVerdict)
            quitf(_wa, "test %d: verdict differs (expected %s, got %s)", t, ansVerdict.c_str(), oufVerdict.c_str());

        if (C == 1 && ansVerdict == "YES") {
            // Read reference's construction (just to keep ans in sync)
            for (int i = 0; i < N; i++) ans.readInt();
            ans.readToken();

            // Read contestant's permutation p[0..N-1] and assignment b
            vector<int> p(N);
            vector<char> seen(N + 1, 0);
            for (int i = 0; i < N; i++) {
                p[i] = ouf.readInt(1, N, "p_i");
                if (seen[p[i]])
                    quitf(_wa, "test %d: cow %d appears twice in permutation", t, p[i]);
                seen[p[i]] = 1;
            }
            string b = ouf.readToken();
            if ((int)b.size() != N)
                quitf(_wa, "test %d: assignment string length %d, expected %d", t, (int)b.size(), N);
            for (char ch : b)
                if (ch != 'J' && ch != 'N')
                    quitf(_wa, "test %d: assignment string contains invalid char '%c'", t, ch);

            for (int i = 0; i < N; i++) {
                int v = p[i];
                int li = (i - 1 + N) % N;
                int ri = (i + 1) % N;
                char self_f = b[i];
                char left_f = b[li];
                char right_f = b[ri];
                char claim_l = L[v - 1];
                char claim_r = R[v - 1];
                if (self_f == 'J') {
                    if (claim_l != left_f)
                        quitf(_wa, "test %d: cow %d (J at pos %d) claims left=%c but left actual=%c",
                              t, v, i + 1, claim_l, left_f);
                    if (claim_r != right_f)
                        quitf(_wa, "test %d: cow %d (J at pos %d) claims right=%c but right actual=%c",
                              t, v, i + 1, claim_r, right_f);
                } else { // 'N' lies
                    if (claim_l == left_f)
                        quitf(_wa, "test %d: cow %d (N at pos %d) claims left=%c matches actual %c (must lie)",
                              t, v, i + 1, claim_l, left_f);
                    if (claim_r == right_f)
                        quitf(_wa, "test %d: cow %d (N at pos %d) claims right=%c matches actual %c (must lie)",
                              t, v, i + 1, claim_r, right_f);
                }
            }
        }
    }

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

verbatim earliest root score=100 submission #70971


Declining Invitations

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

## Description

$N$ contestants participated in a contest, each placing a distinct rank from $1$ to $N$. There are $C$ criteria used to invite contestants to participate in the final round, and the $i$-th-ranked contestant satisfies a specified $n_i$ of them ($1\le n_i\le C$).

The invitation process runs as follows. First, the top $f_1$ students who satisfy the $1$st criteria will be invited. Then, out of all students who haven't yet been invited, the top $f_2$ (or all remaining if there are fewer than $f_2$ remaining) students who satisfy the $2$nd criterion will be invited. This process repeats, for each $i$ from $1$ to $C$ ($1\le f_i\le N$).

However, some contestants will decline to participate in the final round, in which case they will be ignored when determining who to invite.

You are given a permutation $p_1, p_2, \dots, p_N$ of $1\dots N$. For each $i$ from $0$ to $N - 1$, determine the sum of the ranks of the contestants who will be invited if the participants with ranks given by the first $i$ elements of $p$ decline to attend.

## Input Format

The first line contains $N$ and $C$ ($1\le N, C\le 10^5$).

The next line contains $f_1, f_2, \dots, f_C$.

The next line contains $p_1, \dots, p_N$.

The next $N$ lines each contain $n_i$ ($1\le n_i\le C$), followed by $n_i$ distinct integers in $[1, C]$, representing the criteria that the $i$-th-ranked contestant satisfies. It is guaranteed that $\sum n_i\le 10^6$.

## Output Format

Output $N$ lines, the sum of ranks of invitees before each declination.

## Examples

**Input 1**

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

**Output 1**

```
6
6
9
6
4
```

**Input 2**

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

**Output 2**

```
10
14
12
9
5
```

**Input 3**

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

**Output 3**

```
21
20
16
10
5
3
```

## Note

For the first example, there is only one criterion. The top three remaining contestants who have not declined will be invited.

For the second example, initially, the $i$-th contestant gets invited under criterion $i$ for all $1\le i\le 4$. After the first declination, the $(i+1)$-th contestant gets invited under criterion $i$ for all $1\le i\le 4$.

## Scoring

- Inputs 4-6: $N, C\le 10^3$, $\sum n_i\le 10^4$
- Inputs 7-8: $C = 1$
- Inputs 9-10: $C = 2$
- Inputs 11-16: No additional constraints

**Problem credits:** Benjamin Qi

#include "testlib.h"
#include <set>
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int N = inf.readInt(1, 100000, "N"); inf.readSpace();
    int C = inf.readInt(1, 100000, "C"); inf.readEoln();
    for (int i = 1; i <= C; i++) { inf.readInt(1, N, "f_i"); if (i < C) inf.readSpace(); }
    inf.readEoln();
    // permutation p of 1..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, "p is not a permutation: %d repeats", p);
        if (i < N) inf.readSpace();
    }
    inf.readEoln();
    long long sumn = 0;
    for (int i = 1; i <= N; i++) {
        int ni = inf.readInt(1, C, "n_i");
        sumn += ni;
        std::set<int> cs;
        for (int j = 1; j <= ni; j++) {
            inf.readSpace();
            int c = inf.readInt(1, C, "criterion");
            ensuref(cs.insert(c).second, "row %d: criterion %d repeats", i, c);
        }
        inf.readEoln();
    }
    ensuref(sumn <= 1000000, "sum n_i is %lld > 1e6", sumn);
    inf.readEof();
    return 0;
}

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

template <class T> using V = vector<T>;

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

    int N, C;
    cin >> N >> C;
    V<int> f(C);
    for (int &t : f) cin >> t;
    V<int> p(N);
    for (int &t : p) {
        cin >> t;
        --t;  // zero-index
    }
    V<queue<int>> q(C);
    V<int> invited_under(N, C);
    // zero-indexed criterion that each contestant is invited under
    // also, C = not invited, -1 = declined

    for (int i = 0; i < N; ++i) {
        int n;
        cin >> n;
        for (int j = 0; j < n; ++j) {
            int c;
            cin >> c;
            --c;
            q.at(c).push(i);
        }
    }

    // initial invitations
    int64_t ans = 0;
    for (int c = 0; c < C; ++c) {
        int invited_under_c = 0;
        while (size(q.at(c)) && invited_under_c < f.at(c)) {
            int x = q.at(c).front();
            q.at(c).pop();
            if (invited_under.at(x) < c) continue;
            invited_under.at(x) = c;
            ans += x + 1;
            ++invited_under_c;
        }
    }

    // process declinations one at a time
    for (int d : p) {
        cout << ans << "\n";
        int c = invited_under.at(d);
        invited_under.at(d) = -1;
        if (c == C) continue;
        ans -= d + 1;
        while (size(q.at(c))) {
            int x = q.at(c).front();
            q.at(c).pop();
            if (invited_under.at(x) < c) continue;
            assert(invited_under.at(x) > c);
            swap(c, invited_under.at(x));
            if (c == C) {
                ans += x + 1;
                break;
            }
        }
    }
}

verbatim earliest root score=100 submission #70943


Farmer John Loves Rotations

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

## Description

Farmer John has an array $A$ containing $N$ integers ($1\le N\le 5\cdot 10^5$, $1\le A_i\le N$). He picks his favorite index $j$ and takes out a sheet of paper with only $A_j$ written on it. He can then perform the following operation some number of times:

> Cyclically shift all elements in $A$ one spot to the left or one spot to the right. Then, write down $A_j$ on a piece of paper.

Let $S$ denote the set of distinct integers that occur in $A$. Farmer John wonders what the minimum number of operations he must perform is so that the paper contains all integers that appear in $S$.

Since it is unclear what FJ's favorite index is, output the answer for all possible favorite indices $1\le j\le N$. Note for each index, $A$ is reset to its original form before performing any operations.

## Input Format

The first line contains $N$.

The following line contains $A_1, A_2, \ldots, A_N$.

## Output Format

Output $N$ space-separated integers, where the $i$-th integer is the answer for his favorite index $j = i$.

## Examples

**Input 1**

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

**Output 1**

```
4 3 3 4 3 3
```

**Input 2**

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

**Output 2**

```
8 7 6 7 8 9 8 7 6 7 8 9
```

## Note

For the first example, the distinct numbers are $S = \{1, 2, 3, 4\}$. Suppose Farmer John's favorite index is $j = 1$. He starts off with $A_1 = 1$ written on a piece of paper. We can track the array $A$ after each cyclic shift Farmer John makes.

- Cyclic shift right: FJ writes down $A_1 = 4$. Array: `4 1 2 3 1 3`.
- Cyclic shift left: FJ writes down $A_1 = 1$ again. Array: `1 2 3 1 3 4`.
- Cyclic shift left: FJ writes down $A_1 = 2$. Array: `2 3 1 3 4 1`.
- Cyclic shift left: FJ writes down $A_1 = 3$. Array: `3 1 3 4 1 2`.

At this point, Farmer John has written down every number in $S$ using $4$ operations.

## Scoring

- Inputs 3-5: $N\le 500$
- Inputs 6-8: $N\le 10^4$
- Inputs 9-17: No additional constraints

**Problem credits:** Chongtian Ma

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int N = inf.readInt(1, 500000, "N"); inf.readEoln();
    for (int i = 1; i <= N; i++) { inf.readInt(1, N, "A_i"); if (i < N) inf.readSpace(); }
    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)

void ckmin(int &a, int b) { a = min(a, b); }
void ckmax(int &a, int b) { a = max(a, b); }

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

    int N;
    cin >> N;
    V<int> A(N);
    for (int &t : A) cin >> t;

    V<int> lst(N + 1, -1), nxt(N, -1);
    V<int> ans(N, N);
    auto add_ival = [&](int l, int r) {
        assert(l <= r);
        int len = r - l;
        ckmin(ans.at(l), len);
        ckmin(ans.at(r % N), len);
    };
    int r = 0;
    for (int i = 0; i < 2 * N; ++i) {
        int &ls = lst.at(A.at(i % N));
        if (ls == -1) {
            ckmax(r, i);
        } else if (ls < N) nxt.at(ls) = i;
        ls = i;
    }
    for (int i = 0; i < N; ++i) {
        add_ival(i, r);
        assert(nxt.at(i) != -1);
        ckmax(r, nxt.at(i));
    }
    for (int it = 0; it < 2; ++it) {
        for (int i = 0; i < N; ++i) ckmin(ans.at((i + 1) % N), ans.at(i) + 1);
        for (int i = N - 1; i >= 0; --i)
            ckmin(ans.at(i), ans.at((i + 1) % N) + 1);
    }
    for (int i = 0; i < N; ++i) {
        if (i) cout << " ";
        cout << ans[i];
    }
    cout << "\n";
}

verbatim earliest root score=100 submission #70944


Balancing the Barns

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

## Description

Farmer John has $N$ ($1\le N\le 5\cdot 10^4$) barns arranged along a road. The $i$-th barn contains $a_i$ bales of hay and $b_i$ bags of feed ($0\le a_i, b_i\le 10^9$).

Bessie has been complaining about the inequality between barns. She defines the "imbalance" of the farm as the difference between the maximum hay in any barn and the minimum feed in any barn. Formally, the imbalance is $\max(a) - \min(b)$.

To address Bessie's concerns, Farmer John can perform exactly $K$ ($1\le K\le 10^{18}$) transfers. In each transfer, he selects a barn $i$, sells one of its haybales, and buys it a new bag of feed for the same barn. Note that there can be negative amounts in his farm (he is not afraid of debt). Formally, $K$ times, you choose an index $i\in [1, N]$, decrement $a_i$, and increment $b_i$.

Help Farmer John determine the minimum possible imbalance after performing exactly $K$ transfers.

## Input Format

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

The first line of each test case contains $N$ and $K$.

The following line contains $a_1\dots a_N$.

The following line contains $b_1\dots b_N$.

The sum of $N$ over all test cases is at most $5\cdot 10^4$.

## Output Format

For each test case, output a single integer, the minimum possible value of $\max(a) - \min(b)$ after performing $K$ operations.

## Examples

**Input 1**

```
4
1 10
5
3
2 6
100 96
0 4
3 3
1 1 2
0 0 1
3 3
1 2 2
0 1 1
```

**Output 1**

```
-18
90
0
0
```

## Note

In the first test case, Farmer John can transfer $10$ haybales from barn $1$ into bags of feed. This leaves $a = [-5]$ and $b = [13]$. The imbalance is $\max(a) - \min(b) = -5 - 13 = -18$.

In the second test case, Farmer John can transfer $5$ haybales from barn $1$ and $1$ haybale from barn $2$. This leaves $a = [95, 95]$ and $b = [5, 5]$. The imbalance is $95 - 5 = 90$. This is the minimum imbalance Farmer John can achieve.

## Scoring

- Inputs 2-4: $K\le 500$, sum of $N$ over all test cases is $\le 500$
- Inputs 5-8: Sum of $N$ over all test cases is $\le 500$
- Inputs 9-13: No additional constraints

**Problem credits:** Rohin Garg

#include "testlib.h"
int main(int argc, char *argv[]) {
    registerValidation(argc, argv);
    int T = inf.readInt(1, 1000, "T"); inf.readEoln();
    long long sumN = 0;
    for (int tc = 1; tc <= T; tc++) {
        int N = inf.readInt(1, 50000, "N"); inf.readSpace();
        inf.readLong(1, 1000000000000000000LL, "K"); inf.readEoln();
        sumN += N;
        for (int i = 1; i <= N; i++) { inf.readInt(0, 1000000000, "a_i"); if (i < N) inf.readSpace(); }
        inf.readEoln();
        for (int i = 1; i <= N; i++) { inf.readInt(0, 1000000000, "b_i"); if (i < N) inf.readSpace(); }
        inf.readEoln();
    }
    ensuref(sumN <= 50000, "sum N is %lld > 5e4", sumN);
    inf.readEof();
    return 0;
}

#include <algorithm>
#include <array>
#include <iomanip>
#include <iostream>
#include <vector>

using namespace std;

void solve() {
  int n;
  int64_t k;
  cin >> n >> k;
  vector<int64_t> a(n), b(n);
  for(auto& x: a) cin >> x;
  for(auto& x: b) cin >> x;
  auto can = [&](int64_t thresh) -> bool {
    vector<int64_t> na = a, nb = b;
    int64_t have = k;
    for(int i = 0; i < n; i++) {
      if(na[i] - nb[i] > thresh) {
        int64_t use = (na[i] - nb[i] - thresh + 1) / 2;
        if(use > have) return false;
        na[i] -= use;
        nb[i] += use;
        have -= use;
      }
    }
    if(have < 0) return false;
    int64_t lhs = *min_element(nb.begin(), nb.end());
    int64_t abound = lhs + thresh;
    __int128_t need = 0;
    vector<int64_t> xincs;
    int64_t lastx = lhs;
    int64_t inc = 0;
    for(int i = 0; i < n; i++) {
      xincs.push_back(nb[i]);
      if(na[i] > abound) {
        need += na[i] - abound;
        inc--;
        xincs.push_back(na[i]-thresh);
      }
    }
    if(need <= have) return true;
    sort(xincs.begin(), xincs.end());
    for(int i = 0; i < xincs.size() && inc < 0; i++) {
      auto currx = xincs[i];
      need += (currx - lastx) * __int128_t(inc);
      if(need <= have) return true;
      inc++;
      lastx = currx;
    }
    return false;
  };
  int64_t lhs = -2.1e18;
  int64_t rhs = 2.1e18;
  while(lhs < rhs) {
    int64_t mid = lhs + (rhs - lhs) / 2;
    if(can(mid)) rhs = mid;
    else lhs = mid + 1;
  }
  cout << lhs << "\n";
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while(t--) solve();
}

verbatim earliest root score=100 submission #70939