题解 CF1063D 【Candies for Children】

· · 题解

思路:

题目中的数据范围是1e11,这个数据很微妙(1e11 = 1e5 * 1e6),所以分两种情况讨论:

① n < 2e6 :

   这时候可以直接跑答案。

  对于给定的p,y有很多取值,但是可以直接取模算出y的满足p、d约束最大值。O(n)复杂度。

② n > 2e6 :

   这时候跑圈数i,每个对应的圈数可以求出最大的喜欢甜食的人数:

  1、(p + n) * i + y + d = k

  2、p - y <= n - d

  联立这个就可以求p的最大值。(其中d表示l跑到r的人数,y表示d中的喜甜人数)然后处理一下细节就可以O(k/n)。

  然后暴力跑就好了。注意一个点就是最后一个人可以喜欢甜食但是只拿一个。

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
const ll X = 2e6 + 5;

int main()
{
    ll n, l, r, k;
    cin >> n >> l >> r >> k;
    ll d = (r - l + n) % n + 1;

    ll ans = -1;
    if (n < X) {
        for (ll p = n; p >= 0; p--) {
            ll y = (k - 1)%(n + p) + 1 - d;
            if (y < 0 || y > p || y > d || d-(y+1) > n-p)
                continue;
            ll y2 = y+1;
            if (y2 <= p && y2 <= d) {
                ans = max(ans , p);
            }
            if (d-y <= n-p) {
                ans = max(ans, p);
            }
        }
    }
    else {
        for (ll i = 0; i <= k/n; i++) {
            ll p = (k - 2*d - (i-1)*n + 1) / (i+1);
            ll y = k - i*(n+p) - d;
            if (y < 0) {
                if (i == 0)
                    continue;
                ll dis = (-y - 1) / i + 1;
                y += i*dis;
                p -= dis;
            }
            if (p > n) {
                y += (p-n) * i;
                p == n;
            }
            if (y < 0 || y > p || y > d || d-(y+1) > n-p)
                continue;
            ll y2 = y+1;
            if (y2 <= p && y2 <= d) {
                ans = max(ans , p);
            }
            if (d-y <= n-p) {
                ans = max(ans, p);
            }
        }
    }
    cout << ans << endl;
    return 0;
}