题解:P14004 [eJOI 2025] Vacation
masonxiong · · 题解
给定
n 个区间[l_i,r_i] ,你可以将它们平移任意整数长度,要求所有平移长度之和\sum d_i 不超过k ,求全体区间交集长度最大值。
答案具有单调性,于是我们考虑二分这个交集长度最大值。现在我们要做的是:对于一个
这个长度为
我们知道,对于一个区间
记
时间复杂度为
:::info[代码]
int plan_vacation(int N, std::vector<int> L, std::vector<int> R, long long K) {
const std::uint64_t friendCount = std::uint64_t(N), constraint = std::uint64_t(K);
std::vector<std::uint64_t> leftEndpoint(L.begin(), L.end()), rightEndpoint(R.begin(), R.end()), leftPrefixSum(friendCount), rightPrefixSum(friendCount);
const std::uint64_t minLength = [&]() { std::uint64_t result = std::uint64_t(-1); for (std::uint64_t i = friendCount; i--; result = std::min(result, rightEndpoint[i] - leftEndpoint[i] + 1)); return result; }();
std::uint64_t answerRangeLeft = 0, answerRangeRight = minLength + 1;
std::ranges::sort(leftEndpoint), std::ranges::sort(rightEndpoint), std::partial_sum(leftEndpoint.begin(), leftEndpoint.end(), leftPrefixSum.begin()), std::partial_sum(rightEndpoint.begin(), rightEndpoint.end(), rightPrefixSum.begin());
while (answerRangeLeft < answerRangeRight) {
const std::uint64_t possibleAnswer = (answerRangeLeft + answerRangeRight + 1) >> 1;
[&]() {
if (possibleAnswer > minLength)
return false;
const std::uint64_t shift = possibleAnswer - 1, minimumLeft = leftEndpoint.front(), maximumRight = rightEndpoint.back() - shift;
if (minimumLeft > maximumRight)
return false;
auto cost = [&](std::uint64_t position) -> std::uint64_t {
const std::uint64_t rightIndex = std::uint64_t(std::lower_bound(rightEndpoint.begin(), rightEndpoint.end(), position + shift) - rightEndpoint.begin());
const std::uint64_t leftCost = position * rightIndex - ((rightIndex ? rightPrefixSum[rightIndex - 1] : 0) - shift * rightIndex);
const std::uint64_t leftIndex = std::uint64_t(std::upper_bound(leftEndpoint.begin(), leftEndpoint.end(), position) - leftEndpoint.begin());
const std::uint64_t rightCost = (leftPrefixSum.back() - (leftIndex ? leftPrefixSum[leftIndex - 1] : 0)) - position * (friendCount - leftIndex);
return leftCost + rightCost;
};
std::uint64_t positionRangeLeft = minimumLeft, positionRangeRight = maximumRight;
while (positionRangeLeft < positionRangeRight) {
const std::uint64_t possiblePosition = (positionRangeLeft + positionRangeRight) >> 1;
std::lower_bound(rightEndpoint.begin(), rightEndpoint.end(), possiblePosition + shift) - rightEndpoint.begin() < leftEndpoint.end() - std::upper_bound(leftEndpoint.begin(), leftEndpoint.end(), possiblePosition) ? positionRangeLeft = possiblePosition + 1 : positionRangeRight = possiblePosition;
}
return (positionRangeLeft > minimumLeft ? std::min(cost(positionRangeLeft), cost(positionRangeLeft - 1)) : cost(positionRangeLeft)) <= constraint;
}() ? answerRangeLeft = possibleAnswer : answerRangeRight = possibleAnswer - 1;
}
return int(answerRangeLeft);
}
:::