Official

O - 植物の水やり / Watering Plants Editorial by admin

gpt-5.5-high

Overview

We can think of each plant as having a “deadline by which it must be watered before it withers” with a period of \(P\).
We will check if the required number of waterings by each time does not exceed the number of waterings that can be done by that time, and find the first time at which this condition fails.

Analysis

Suppose we water plant \(i\) a total of \(a_i(t)\) times by \(t\) seconds.
At this time, its water level is:

\(T_i + P a_i(t) - t\)

For the plant not to wither, this value must be at least \(1\), so we need:

\(T_i + P a_i(t) - t \ge 1\)

which means:

\(a_i(t) \ge \left\lceil \frac{t - T_i + 1}{P} \right\rceil\)

is required.

This can be rephrased as follows:

  • Plant \(i\) needs its first watering by time \(T_i\).
  • After that, it needs an additional watering every \(P\) seconds.

In other words, plant \(i\) can be thought of as having “watering deadlines” at:

\(T_i, T_i + P, T_i + 2P, \dots\)

Let \(D(t)\) be the total number of watering deadlines that occur up to time \(t\).
Since Takahashi can perform at most \(t\) waterings in \(t\) seconds, a necessary condition is:

\(D(t) \le t\)

Additionally, since we can water plants early, if this condition holds for all times, we can achieve it by watering in order of the earliest deadlines.

Therefore, the problem reduces to finding how long \(F(t) \ge 0\) can be maintained, where we define:

\(F(t) = t - D(t)\)

Here, \(F(t)\) represents the “margin.”


A naive second-by-second simulation will TLE (Time Limit Exceeded) because \(T_i\) can be up to \(10^9\), and the process can continue for a long time after that.

Thus, we focus on the changes in \(F(t)\).

Let \(C(t)\) be the number of watering deadlines that occur at time \(t\). Then:

\(F(t) - F(t-1) = 1 - C(t)\)

Since each plant’s deadlines are periodic with period \(P\), the increments of \(F(t)\) can also be managed as a sequence with period \(P\).

Algorithm

We prepare an array val of length \(P\).

val[r] represents \(F(t) - F(t-1)\) for times \(t\) satisfying:

\((t-1) \bmod P = r\)

Initially, since there are no deadlines, the margin increases by \(1\) every second.
Therefore, we initialize all elements of val[r] to \(1\).

When we reach the initial water level \(T_i\) of a plant, that plant starts having deadlines at times:

\(T_i, T_i+P, T_i+2P,\dots\)

Therefore, we decrement val at the corresponding residue:

\((T_i-1) \bmod P\)

by \(1\).


We process the plants in ascending order of \(T_i\).

Let the current time be cur, and the current margin \(F(\text{cur})\) be G.

If the initial water level of the next plant to be processed is \(e\), no new deadlines will appear from time cur+1 to \(e-1\).
Since val does not change in this interval, we can advance the time in bulk.

After that, we add all plants with \(T_i=e\).
That is, we perform:

val[(e-1) % P] -= count

Then, we advance the time to \(e\) by 1 second.

If \(G < 0\) at any point, the required number of waterings exceeds the possible number of waterings at that time.
Thus, the answer is the immediately preceding time.


To advance through intervals in bulk, we use a segment tree.

Each node of the segment tree maintains the following two values for its corresponding interval:

  • sum: The sum of val over the entire interval.
  • minp: The minimum value of prefix sums within the interval.

When the current margin is \(G\), the condition that we do not fail while advancing through a certain interval is:

\(G + \text{minp} \ge 0\)

If it does not fail, we can advance through the entire interval at once and update:

\(G \gets G + \text{sum}\)

If it fails, we search from the beginning of this interval to find the first position where \(G < 0\).


After adding all plants, val becomes completely periodic with period \(P\).

Let the change in margin per period be:

\(S = \sum val\)

  • If the process does not fail within one full period and \(S \ge 0\), the margin will not decrease, meaning we can maintain it indefinitely.
  • If \(S < 0\), the margin decreases with each period, so it will eventually fail.

In this case as well, we can calculate how many periods we can skip before failing.

Let \(m\) be the minimum prefix sum within one period. When the current margin is \(G\), the minimum margin within the period is:

\(G + m\)

Since the margin decreases by \(-S\) (where \(S < 0\)) per period, the number of periods we can survive before failing is given by:

\(\left\lfloor \frac{G+m}{-S} \right\rfloor + 1\)

Complexity

  • Time Complexity: \(O(N \log N + N \log P + P)\)
  • Space Complexity: \(O(P)\)

Sorting \(T_i\) takes \(O(N \log N)\), and adding each group of plants and processing intervals takes \(O(\log P)\) per operation.
The process of searching linearly for the failing position happens at most once at the very end, which takes an additional \(O(P)\) time.

Implementation Details

Each node of the segment tree maintains the following for its interval:

  • Sum of the interval: sum
  • Minimum prefix sum: minp

When merging the left child a and the right child b, the merged attributes are:

  • Sum: a.sum + b.sum
  • Minimum prefix sum: min(a.minp, a.sum + b.minp)

Also, note that the index of val corresponding to time \(t\) is:

\((t-1) \bmod P\)

In the implementation, if we have processed up to time cur, the next time to process is cur+1, so the starting index in the periodic array will be cur % P.

If the failure occurs \(h\) seconds after the current time, we cannot maintain the condition at that time, so the answer is:

cur + h - 1

Source Code

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

using ll = long long;
const ll INF = (1LL << 62);

struct Node {
    ll sum;
    ll minp;
};

Node mergeNode(const Node& a, const Node& b) {
    return {a.sum + b.sum, min(a.minp, a.sum + b.minp)};
}

struct SegTree {
    int n, sz;
    vector<Node> d;

    SegTree() : n(0), sz(1) {}

    void init(int n_) {
        n = n_;
        sz = 1;
        while (sz < n) sz <<= 1;
        d.assign(2 * sz, {0, INF});
        for (int i = 0; i < n; i++) d[sz + i] = {1, 1};
        for (int i = sz - 1; i >= 1; i--) {
            d[i] = mergeNode(d[i << 1], d[i << 1 | 1]);
        }
    }

    void add(int p, ll x) {
        int k = p + sz;
        ll v = d[k].sum + x;
        d[k] = {v, v};
        while (k >>= 1) {
            d[k] = mergeNode(d[k << 1], d[k << 1 | 1]);
        }
    }

    Node query(int l, int r) const {
        Node sml{0, INF}, smr{0, INF};
        l += sz;
        r += sz;
        while (l < r) {
            if (l & 1) sml = mergeNode(sml, d[l++]);
            if (r & 1) smr = mergeNode(d[--r], smr);
            l >>= 1;
            r >>= 1;
        }
        return mergeNode(sml, smr);
    }
};

int P;
vector<ll> val;
SegTree seg;

ll findInLinear(int l, int len, ll G) {
    ll pref = 0;
    for (int i = 0; i < len; i++) {
        pref += val[l + i];
        if (G + pref < 0) return i + 1;
    }
    return -1;
}

ll processLinear(int l, int len, ll& G) {
    if (len <= 0) return -1;
    Node nd = seg.query(l, l + len);
    if (G + nd.minp < 0) {
        return findInLinear(l, len, G);
    }
    G += nd.sum;
    return -1;
}

ll advanceFinite(ll L, int start, ll& G) {
    ll elapsed = 0;
    if (L <= 0) return -1;

    if (start != 0) {
        int len = (int)min<ll>(L, (ll)P - start);
        ll h = processLinear(start, len, G);
        if (h != -1) return elapsed + h;
        elapsed += len;
        L -= len;
    }

    if (L >= P) {
        ll cycles = L / P;
        Node whole = seg.query(0, P);
        ll S = whole.sum;
        ll m = whole.minp;

        if (G + m < 0) {
            return elapsed + findInLinear(0, P, G);
        }

        if (S < 0) {
            ll j = (G + m) / (-S) + 1;
            if (j < cycles) {
                G += j * S;
                elapsed += j * (ll)P;
                return elapsed + findInLinear(0, P, G);
            }
        }

        G += cycles * S;
        elapsed += cycles * (ll)P;
        L -= cycles * (ll)P;
    }

    if (L > 0) {
        int len = (int)L;
        ll h = processLinear(0, len, G);
        if (h != -1) return elapsed + h;
    }

    return -1;
}

ll advanceInfinite(int start, ll& G) {
    ll elapsed = 0;

    if (start != 0) {
        int len = P - start;
        ll h = processLinear(start, len, G);
        if (h != -1) return elapsed + h;
        elapsed += len;
    }

    Node whole = seg.query(0, P);
    ll S = whole.sum;
    ll m = whole.minp;

    if (G + m < 0) {
        return elapsed + findInLinear(0, P, G);
    }

    if (S >= 0) return -1;

    ll j = (G + m) / (-S) + 1;
    G += j * S;
    elapsed += j * (ll)P;

    return elapsed + findInLinear(0, P, G);
}

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

    int N;
    cin >> N >> P;

    vector<ll> T(N);
    for (int i = 0; i < N; i++) cin >> T[i];
    sort(T.begin(), T.end());

    val.assign(P, 1);
    seg.init(P);

    ll G = 0;
    ll cur = 0;

    for (int i = 0; i < N; ) {
        ll e = T[i];
        ll cnt = 0;
        while (i < N && T[i] == e) {
            i++;
            cnt++;
        }

        ll L = e - cur - 1;
        if (L > 0) {
            ll h = advanceFinite(L, (int)(cur % P), G);
            if (h != -1) {
                cout << cur + h - 1 << '\n';
                return 0;
            }
            cur += L;
        }

        int idx = (int)((e - 1) % P);
        val[idx] -= cnt;
        seg.add(idx, -cnt);

        ll h = advanceFinite(1, (int)(cur % P), G);
        if (h != -1) {
            cout << cur + h - 1 << '\n';
            return 0;
        }
        cur++;
    }

    ll h = advanceInfinite((int)(cur % P), G);
    if (h == -1) {
        cout << -1 << '\n';
    } else {
        cout << cur + h - 1 << '\n';
    }

    return 0;
}

This editorial was generated by gpt-5.5-high.